How to use pop function in Pandas Dataframe in Python

In this tutorial, we will learn how pop function can be used in Pandas Dataframe in Python. Pop function has can be used for two reasons, firstly for removing the last value or the index specified. Secondly, it can be used to return the value or index that was removed. Pop function can be helpful when you do not need some columns that in your Dataframe for calculations. Therefore, this function can help clean data by taking out the columns not of our immediate need. Let us understand to do this with the help of an example.

                   Using POP Function in Pandas Dataframe in Python

Let us take a Dataframe with marks of students in two different subjects. To learn how to make Dataframe please Click here. My Dataframe consisting of marks of all three students in two subjects is stored as Df. Now as a teacher of a particular subject, I want to see marks of students in only my subject. Here if I want to see only the marks of Maths subjects for my student Ankit, Arpit and Arun. Now I will use the pop function on the Physics column from my dataset. I have stored this new dataset under the name of Delete.

Code for using POP Function

Code:

import pandas as pd
import numpy as np
data={'maths':[10,20,10],'physics':[30,10,10]}
Df=pd.DataFrame(data,index=["Ankit","Arpit","Arun"])
Df

Output:

maths
physics
Ankit
10
30
Arpit
20
10
Arun
10
10
Code:
Delete=Df.pop('physics')
Df

Output:

maths
Ankit
10
Arpit
20
Arun
10

Code:

Delete

Output:

Ankit    30
Arpit    10
Arun     10
Name: physics, dtype: int64

Results that we see is that we print the Dataframe after using the pop function then we get a new Dataframe with no Physics column. While on printing the Delete function we get the physics column which was originally deleted.

Also read: Binning Data with Pandas qcut and cut in Python

Leave a Reply