Pandas How To Uncategorized How to drop a column

How to drop a column

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)

Tags: , ,

1 thought on “How to drop a column”

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post