+2 votes
in Programming Languages by (15.7k points)
How can I delete some of the columns of a Pandas DataFrame?

1 Answer

0 votes
by (27.1k points)

You can use the drop() function to drop your desired columns of a Pandas dataframe. You need to pass the column names as a list to this function. Here is an example to show how to use the function:

>>> import numpy as np
>>> import pandas as pd
>>> df1=pd.DataFrame({'A':[11,12,13,13],'B':[21,22,23,24],'C':[31,32,33,34],'D':[41,42,43,44]})
>>> df1
    A   B   C   D
0  11  21  31  41
1  12  22  32  42
2  13  23  33  43
3  13  24  34  44
>>> df2=df1.drop(columns=['A','D'])
>>> df2
    B   C
0  21  31
1  22  32
2  23  33
3  24  34
>>> df3=df1.drop(['B','D'], axis=1)
>>> df3
    A   C
0  11  31
1  12  32
2  13  33
3  13  34

by (27.1k points)
You can also use the pop() function. The function returns the column and drops the column from the frame.

>>> import pandas as pd
>>> df = pd.DataFrame({'A':[10,20,30], 'B':[11,22,33], 'C':[12,24,36], 'D':[13,26,39]})
>>> df
    A   B   C   D
0  10  11  12  13
1  20  22  24  26
2  30  33  36  39
>>> df.pop('A')
0    10
1    20
2    30
Name: A, dtype: int64
>>> df
    B   C   D
0  11  12  13
1  22  24  26
2  33  36  39
...