Pandas, How to drop a column from a DataFrame.

Syntax:


df = df.drop( ['COLUMNNAME1', 'COLUMNNAME2'], axis=1 )

The columns from a DataFrame are removed using the drop method, the column names are passed using an array along with the parameter axis=1.

Example:

This example creates a DataFrame from a matric of 4 columns and 5 rows. The columns are called A B C and D. The content of the DataFrame is printed in the output. The columns B and D are drop using the drop method. The drop method uses an array to filter the columns, so any number of columns can be removed. The output DataFrame is then written in the output.


import pandas as pd 
import numpy as np 

df = pd.DataFrame(np.arange(20).reshape(5,4),
                   columns=['A', 'B', 'C', 'D'])
print( df )

# Drop column B and D
df = df.drop( ['B', 'D'], axis=1 )

print()

print( df )

The output will be:

    A   B   C   D
0   0   1   2   3
1   4   5   6   7
2   8   9  10  11
3  12  13  14  15
4  16  17  18  19

    A   C
0   0   2
1   4   6
2   8  10
3  12  14
4  16  18

References:

Pandas DataFrame

Share this article:

Recent Comments