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()
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
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
Pop will do 2 things:¶
- Remove the column from the data frame! - df.pop("your column name")
- Return the column you're removing from the dataframe - "x = (your column returned)"
x = df.pop('type')
The dataframe now has the column you popped removed¶
df
And your popped column was returned as a pandas series¶
x
Check out more Pandas functions on our Pandas Page