How to delete columns of a data frame in Python

For online Python training registration, click here !

Data frame is the tabular data object in Python. It can store different mode of data for different columns. If you want to remove unwanted columns from a data frame, you can use either del() function or drop() method. Next we show some examples about that.

#Import Pandas module
import pandas as pd
#create a dictionary
Dict4 = {'last' : ['zhang', 'yue', 'lin', 'li', 'wang'],
        'first' : ['wei', 'shirley', 'mico', 'miaomiao', 'maomao'],
        'age' : [32, 34, 8, 14, 3],
        'city': ['molde','aukra','molde','aukra','molde']}
#create a data frame with inputting dictionary above
Df4 = pd.DataFrame(Dict4)
Df4
#output
    last     first  age   city
0  zhang       wei   32  molde
1    yue   shirley   34  aukra
2    lin      mico    8  molde
3     li  miaomiao   14  aukra
4   wang    maomao    3  molde
#delete one column, using del() function
del Df4['first']
Df4
#output
    last  age   city
0  zhang   32  molde
1    yue   34  aukra
2    lin    8  molde
3     li   14  aukra
4   wang    3  molde
#create again same data frame 
Df4 = pd.DataFrame(Dict4)
#using drop method to remove two columns
Df4= Df4.drop(['city','age'], axis=1)
Df4
#output
    last     first
0  zhang       wei
1    yue   shirley
2    lin      mico
3     li  miaomiao
4   wang    maomao

Sometimes you may need the removed column, then you can use pop() method to data frame.

#create again data frame
Df4 = pd.DataFrame(Dict4)
#remove column 'city' and save this to an object.
Pop_col= Df4.pop('city')
#show popped columm, it is a series
Pop_col
#output
0    molde
1    aukra
2    molde
3    aukra
4    molde
Name: city, dtype: object
#show original data frame, the column 'city' has been removed
Df4
#output
    last     first  age
0  zhang       wei   32
1    yue   shirley   34
2    lin      mico    8
3     li  miaomiao   14
4   wang    maomao    3

For more examples on Python, you can view playlists from our YouTube channel.

wilsonzhang746

Recent Posts

Download R Course source files

Click here to download R Course source files !

2 months ago

Download Python Course source files

Click here to download Python Course Source Files !

2 months ago

How to create a data frame from nested dictionary with Pandas in Python

For online Python training registration, click here ! Pandas provides flexible ways of generating data…

5 months ago

Using isin() to check membership of a data frame in Python

Click her for course registration ! When a data frame in Python is created via…

5 months ago

How to assign values to Pandas data frame in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…

5 months ago

How to select elements and show information of a Pandas data frame in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…

5 months ago