Pandas DataFrame pop() Method

In this tutorial, we will learn the Python pandas DataFrame.pop() method. This method deletes or drops the specified item in the DataFrame and returns the item. It raises the KeyError if the specified item not found.

The below is the syntax of the DataFrame.pop() method.

Syntax

DataFrame.pop(item)

Parameters

item: It represents the label that is the Label of the column to be popped.

Example 1: Deleting from the DataFrame in Pandas

Here, the DataFrame.pop() method drops the specified item in the DataFrame and returns the specified item. We can use this method to delete any element from the dataframe.

#importing pandas as pd
import pandas as pd
#creating DataFrame
df= pd.DataFrame({'Name':['Pooja','Sindu','Renuka'],'Age':[18,25,20],'Height': [145,155,165],'Weight': [45,55,65]})
print("--------The DataFrame is-------")
print(df)
print("--------------------------------")
print(df.pop("Age"))

Once we run the program we will get the following output.


--------The DataFrame is-------
Name Age Height Weight
0 Pooja 18 145 45
1 Sindu 25 155 55
2 Renuka 20 165 65
--------------------------------
0 18
1 25
2 20
Name: Age, dtype: int64

Example 2: Deleting from the DataFrame in Pandas

Here, the DataFrame.pop() method drops the specified item in the DataFrame and returns the specified item.

#importing pandas as pd
import pandas as pd
#creating DataFrame
df= pd.DataFrame({'Name':['Pooja','Sindu','Renuka'],'Age':[18,25,20],'Height': [145,155,165],'Weight': [45,55,65]})
print("--------The DataFrame is-------")
print(df)
print("--------------------------------")
print(df.pop("Name"))

Once we run the program we will get the following output.


--------The DataFrame is-------
Name Age Height Weight
0 Pooja 18 145 45
1 Sindu 25 155 55
2 Renuka 20 165 65
--------------------------------
0 Pooja
1 Sindu
2 Renuka
Name: Name, dtype: object

Example 3: KeyError in Dataframe while using pop() Method

The DataFrame.pop() method raises KeyError if the specified item not found in the DataFrame. Here, we are removing an element "abc" which does not exist in the dataframe. So, removing the item will raise an error.

#importing pandas as pd
import pandas as pd
#creating DataFrame
df= pd.DataFrame({'Name':['Pooja','Sindu','Renuka'],'Age':[18,25,20],'Height': [145,155,165],'Weight': [45,55,65]})
print(df.pop("abc"))

Once we run the program we will get the following output.


KeyError: 'abc'

Conclusion

In this tutorial, we learned the Python pandas DataFrame.pop() method. We learned the syntax, parameter and by applying this method on the DataFrame, we solved examples and understood the DataFrame.pop() method.