DEV Community

Cover image for Pandas Pop() Method | Python Data Analysis
Labby for LabEx

Posted on

Pandas Pop() Method | Python Data Analysis

Introduction

MindMap

In this lab, we will be exploring the pop() method in the Python Pandas library. The pop() method is used to delete or drop a specified item in a DataFrame and returns the item. If the specified item is not found, the method raises a KeyError.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.

Importing the pandas library

First, we need to import the pandas library in order to use the pop() method.

import pandas as pd
Enter fullscreen mode Exit fullscreen mode

Creating a DataFrame

Next, we will create a DataFrame object using the DataFrame() constructor. We will pass a dictionary containing the column labels and their corresponding values.

df = pd.DataFrame({'Name': ['Pooja', 'Sindu', 'Renuka'], 'Age': [18, 25, 20], 'Height': [145, 155, 165], 'Weight': [45, 55, 65]})
Enter fullscreen mode Exit fullscreen mode

Dropping an item from the DataFrame

Now, we can use the pop() method to drop a specified item from the DataFrame. The method takes the label of the column to be popped as the parameter.

df.pop('Age')
Enter fullscreen mode Exit fullscreen mode

Printing the modified DataFrame

Finally, we can print the modified DataFrame to see the changes.

print(df)
Enter fullscreen mode Exit fullscreen mode

Here is the complete code:

import pandas as pd

df = pd.DataFrame({'Name': ['Pooja', 'Sindu', 'Renuka'], 'Age': [18, 25, 20], 'Height': [145, 155, 165], 'Weight': [45, 55, 65]})

df.pop('Age')

print(df)
Enter fullscreen mode Exit fullscreen mode

Summary

In this lab, we learned how to use the pop() method in the Python Pandas library to delete or drop a specified item in a DataFrame. We also learned how to handle a KeyError if the specified item is not found in the DataFrame. The pop() method can be a useful tool for manipulating and modifying DataFrames in Python.


πŸš€ Practice Now: Pandas DataFrame Pop Method


Want to Learn More?

Top comments (0)