How to Delete Column in DataFrame
There are two methods to delete column in DataFrame.
1. we can delete the column in DataFrame by using the “del” function
import pandas as pd
data = { ‘one’ : pd.Series ( [1,2,3,4], index=[‘a’,’b’,’c’,’d’]),
‘two’ : pd.Series( [10,20,30,40], index=[‘a’,’b’,’c’,’d’]),
‘three’ : pd.Series ( [6,7,8,9], index=[‘a’,’b’,’c’,’d’]),
‘four’ : pd.Series ( [100,200,300,400], index=[‘a’,’b’,’c’,’d’]) }
df=pd.DataFrame(data)
print (“before deleting DataFrame is”)
print (df)
print(“after deleting the third column using del function”)
del df [‘three’]
print (df)
its output will be
before deleting DataFrame is
one two three four
a 1 10 6 100
b 2 11 7 200
c 3 12 8 300
d 4 13 9 400
after deleting the third column using del function
one two four
a 1 10 100
b 2 11 200
c 3 12 300
d 4 13 400
2. we can delete column in DataFrame by using the “pop” function
import pandas as pd
data = { ‘one’ : pd.Series ( [1,2,3,4], index=[‘a’,’b’,’c’,’d’]),
‘two’ : pd.Series( [10,20,30,40], index=[‘a’,’b’,’c’,’d’]),
‘three’ : pd.Series ( [6,7,8,9], index=[‘a’,’b’,’c’,’d’]),
‘four’ : pd.Series ( [100,200,300,400], index=[‘a’,’b’,’c’,’d’]) }
df=pd.DataFrame(data)
print (“before deleting DataFrame is”)
print (df)
print(“after deleting the fourth column using pop function”)
df.pop[‘four’]
print (df)
its output will be
before deleting DataFrame is
one two three four
a 1 10 6 100
b 2 11 7 200
c 3 12 8 300
d 4 13 9 400
after deleting the fourth column using pop function
one two three
a 1 10 6
b 2 11 7
c 3 12 8
d 4 13 9