How to delete a column in pandas
Drop the column
DataFrame has a method called drop() that removes rows or columns according to specify column(label) names and corresponding axis.
import pandas as pd# Create a dataframe from a dictdf = pd.DataFrame({"a": [1,2,3], "b":[2,4,6]})print("The DataFrame object before deleting the column")print(df)df.drop('a', inplace=True, axis=1)print("The DataFrame object after deleting the column a")print(df)
line 7shows how to drop a column by callingdrop.inplace=Truemeans the operation would work on the original object.axis=1means we are dropping the column, not the row.- You can compare the output of
line 6andline 9.
Delete the column
del is also an option, you can delete a column by del df['column name']. The Python would map this operation to df.__delitem__('column name'), which is an internal method of DataFrame.
import pandas as pd# Create a dataframe from a dictdf = pd.DataFrame({"a": [1,2,3], "b":[2,4,6]})print("The DataFrame object before deleting the column")print(df)del df["a"]print("The DataFrame object after deleting the column a")print(df)
line 7shows how to usedelto delete a column from a DataFrame object.
Pop the column
pop() function would also drop the column. Unlike the other two methods, this function would return the column.
import pandas as pd# Create a dataframe from a dictdf = pd.DataFrame({"a": [1,2,3], "b":[2,4,6]})print("The DataFrame object before deleting the column")print(df)df.pop("a")print("The DataFrame object after deleting the column a")print(df)
line 7shows how to usepop()to delete a column.