Pandas DataFrame Delete Column
There are different ways to delete a column of Pandas DataFrame. Following are some of the ways we will discuss in this tutorial.
- Delete column using del keyword.
- Delete column using drop() method.
- Delete column using pop() method.
Delete DataFrame Column using del keyword
To delete a column of DataFrame using del
keyword, use the following syntax.
del myDataFrame['column_name']
In the following example, we shall initialize a DataFrame with three columns and delete one of the column using del
keyword.
Python Program
import pandas as pd #initialize a dataframe df = pd.DataFrame({ 'a':[14, 52, 46], 'b':[32, 85, 64], 'c':[88, 47, 36]}) #delete column 'b' del df['b'] #print the dataframe print(df)
Output
a c 0 14 88 1 52 47 2 46 36
The column with name b
has been deleted from the dataframe.
Delete DataFrame Column using drop method
pandas.DataFrame.drop() method returns a new DataFrame with the specified columns dropped from the original DataFrame. The original DataFrame is not modified.
Python Program
import pandas as pd #initialize a dataframe df = pd.DataFrame({ 'a':[14, 52, 46], 'b':[32, 85, 64], 'c':[88, 47, 36]}) #delete column 'b' df1 = df.drop(['b'], axis=1) #print the dataframe print(df1)
Output
a c 0 14 88 1 52 47 2 46 36
Delete DataFrame Column using pop method
pandas.DataFrame.pop() method deletes specified column from the DataFrame and returns the deleted column.
Python Program
import pandas as pd #initialize a dataframe df = pd.DataFrame({ 'a':[14, 52, 46], 'b':[32, 85, 64], 'c':[88, 47, 36]}) #delete column 'b' poppedColumn = df.pop('b') #print the dataframe print(df) print('\nDeleted Column\n-------------') #print deleted column print(poppedColumn)
Output
a c 0 14 88 1 52 47 2 46 36 Deleted Column ------------- 0 32 1 85 2 64 Name: b, dtype: int64
Conclusion
In this Pandas Tutorial, we learned how to delete a column from DataFrame.