How to drop one or multiple columns in Pandas Dataframe

Published on Aug. 22, 2023, 12:15 p.m.

To drop one or multiple columns in a Pandas dataframe, you can use the drop() method. Here are some examples:

To drop a single column:

import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
df = df.drop('B', axis=1)

print(df)

Output:

   A  C
0  1  7
1  2  8
2  3  9

To drop multiple columns:

import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
df = df.drop(['B', 'C'], axis=1)

print(df)

Output:

   A
0  1
1  2
2  3

In both cases, axis=1 specifies that we want to drop columns, and the column label or list of labels to be dropped is passed as the first argument to drop().

If you want to modify the original dataframe instead of creating a new one, you can set the inplace parameter to True:

import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
df.drop('B', axis=1, inplace=True)

print(df)

Output:

   A  C
0  1  7
1  2  8
2  3  9

Tags: