There are several different ways to drop a column in Pandas. Let me show you these options and you choose how you drop the Pandas column.
Pandas drop
The easiest weay to drop a column in Pandas is by using the drop Pandas function.
import pandas as pd
df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
print(df)
df.drop('A', axis=1, inplace=True)
print(df)
To drop multiple columns, you can pass a list of column names to the drop method:
import pandas as pd
df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]})
print(df)
df.drop(['A', 'B'], axis=1, inplace=True)
print(df)
Remember to use axis and inplace parameters to show Python which column should be dropped and to replace your data frame by the one with the dropped column.
Drop function documentation: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.drop.htmlÂ
Pandas pop
Similarly, you may use the pop Pandas function.
import pandas as pd
df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
print(df)
df.pop('A')
print(df)
This time you don’t need any additional parameters.
Pop function documentation: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pop.htmlÂ
Del function
import pandas as pd
df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
print(df)
del df['A']
print(df)
1 thought on “How to drop a column”