Pandas Pop – pd.Dataframe.Pop()

Pandas Pop is the sound a column makes when it’s removed from a dataset…pop!

Popping a column in pandas is no different. We use pd.DataFrame.pop when we want to remove a column.

What is Pandas Pop?

Pop will is the pandas function to:

  • Remove your column from a dataframe
  • Return that column you’re dropping as a series so you can use it (if you want)

df.pop() is very similar to df.drop(), but .drop() will return the DataFrame with the column removed. Whereas .pop() will return the column.

I use pop when I’m creating a dummy column. A column that will only temporarily be used and I don’t want my dataframe to become sloppy.

If you need to remove multiple columns from your dataset, you can either .pop() multiple times, or use pandas .drop() instead. With .drop() you can pass a list of columns (or rows) and they’ll be dropped from your DataFrame.

Pop doesn’t take any extra arguments so you don’t need to worry about changing anything. Did you know that pop is also used with regular vanilla python? Check out python pop.

Make sure to make a ‘popping’ sound whenever you call df.pop()

In [1]:
import pandas as pd

Create A Sample DataFrame

We are passing a list of data points about bars & restaurants in San Francisco, then defining the column names

In [2]:
df = pd.DataFrame([('Foreign Cinema', 'Restaurant', 289.0),
                   ('Liho Liho', 'Restaurant', 224.0),
                   ('500 Club', 'bar', 80.5),
                   ('The Square', 'bar', 25.30)],
           columns=('name', 'type', 'AvgBill')
                 )
df
Out[2]:
nametypeAvgBill
0Foreign CinemaRestaurant289.0
1Liho LihoRestaurant224.0
2500 Clubbar80.5
3The Squarebar25.3

Pop will do 2 things:

  1. Remove the column from the data frame! - df.pop("your column name")
  2. Return the column you're removing from the dataframe - "x = (your column returned)"
In [3]:
x = df.pop('type')

The dataframe now has the column you popped removed

In [4]:
df
Out[4]:
nameAvgBill
0Foreign Cinema289.0
1Liho Liho224.0
2500 Club80.5
3The Square25.3

And your popped column was returned as a pandas series

In [5]:
x
Out[5]:
0    Restaurant
1    Restaurant
2           bar
3           bar
Name: type, dtype: object

Link to code above

Check out more Pandas functions on our Pandas Page

Official Documentation