Lesson 8 of 146 min
Tables with pandas
pandas reads a CSV into a table with named columns; a comparison on a column marks every row True or False, the table keeps the True rows, and groupby gives one number for each group.
After this lesson you can load a CSV, then select, filter and group.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
A column's name typed wrong
A name the table doesn't have stops the code with a KeyError, the same error a dict gives for a key it doesn't have. The message holds only the name you asked for. df.columns lists the names the table really has, so you can copy one from there.
df["mass"]KeyError: 'mass'
print(df.columns.tolist())['species', 'island', 'bill_length_mm', 'bill_depth_mm', 'flipper_length_mm', 'body_mass_g', 'sex']
Rows and columns at once: loc and iloc
loc takes the rows first, then the columns, both by their names. The rows can be a column of True and False, so a filter and a choice of columns fit in one line. iloc does the same by position, counting from zero, the way a list does.
keep = df["body_mass_g"] > 4500
print(df.loc[keep, ["species", "body_mass_g"]].head(3))species body_mass_g 7 Adelie 4675.0 39 Adelie 4650.0 45 Adelie 4600.0
print(df.iloc[:2, :3])species island bill_length_mm 0 Adelie Torgersen 39.1 1 Adelie Torgersen 39.5
Change values with loc, in one step
Two pairs of square brackets in a row, df[keep]["size"] = "big", change nothing. The first pair makes a new table, and the value lands there. Since pandas 3 it never reaches df, and pandas warns with ChainedAssignmentError. With loc, the rows and the column go in one pair of brackets, and df itself changes.
df.loc[keep, "size"] = "big"
df.loc[~keep, "size"] = "small"
print(df["size"].value_counts())size small 229 big 115 Name: count, dtype: int64
A first look at a new table
Before you filter, see what you have. value_counts counts each value of a column. describe sums up a number column: here its count, mean, smallest and largest. The count is 342, not 344, because it leaves out the two penguins with no mass.
print(df["species"].value_counts())species Adelie 152 Gentoo 124 Chinstrap 68 Name: count, dtype: int64
print(df["body_mass_g"].describe()[["count", "mean", "min", "max"]].round(1))count 342.0 mean 4201.8 min 2700.0 max 6300.0 Name: body_mass_g, dtype: float64
The newer way: pd.col
pandas 3 can name a column inside a filter with pd.col, so the condition doesn't repeat the table's name. It gives the same 115 rows. Colab still runs pandas 2.2, where pd.col doesn't exist yet, so the lesson uses square brackets, which run everywhere.
heavy = df.loc[pd.col("body_mass_g") > 4500]
print(heavy.shape)(115, 7)
Run on Python 3.13 and pandas 3.1.1. Checked on .
Quiz
Two questions on this lesson. Answer as often as you like.
1 of 2
mass is the table's body_mass_g column, one mass for each penguin. What does mass > 4500 give?
2 of 2
A small table of four penguins, made from a dict. What does this print?
import pandas as pd
df = pd.DataFrame({"species": ["Adelie", "Gentoo", "Chinstrap", "Gentoo"],
"body_mass_g": [3700, 5400, 3800, 5000]})
heavy = df[df["body_mass_g"] > 4500]
print(heavy.shape)The ideas in this lesson
- A DataFrame
- pandas reads a CSV into a DataFrame: a table with a name on each column and a number on each row.
- A filter
- A comparison on a column gives True or False for each row, and the table keeps the True rows.
- Groups
- groupby puts the rows in groups by one column, and a summary like mean gives one number for each group.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Hundreds of penguins
Here's a bet. This table holds hundreds of real penguins from Antarctica. Each row is one penguin. Each column is one thing somebody measured. This line checks every penguin's mass against one number. What comes out?
The heavy penguins?
One True or False? Or something else?
A CSV file
Hold on to that guess. First, the table. The penguins come in a CSV file. That's a table, written as plain text. The first line holds the names of the columns.
Then comes one penguin on each line, with commas between the values.
A spreadsheet, saved as text.
A DataFrame
So how do you get it into Python?
Line one brings in pandas, the library for tables. Its short name is pd.
Line three reads the file.
What comes out is a table, with a name on each column... and a number on each row, from zero. pandas calls it a DataFrame, so its name here is df. Along the top are the columns: the species, the island, and what was measured.
Its shape
Like an array, a DataFrame has a shape, rows first. Three hundred and forty-four rows, one for each penguin. Then seven columns, one for each thing measured.
Look at the row numbered three. Its measurements say NaN. That means "not a number": nobody measured this penguin.
One column
How do you get one column?
Line four puts the column's name in square brackets, the way a dict finds a value by its key. So mass holds one column: a value for each row, each with its row's number.
True or False
The table holds all the penguins, and mass holds their masses. Back to the bet.
Line five checks every mass: is it over forty-five hundred grams? That's four and a half kilos. It calls what comes out keep.
What comes out is a whole column... a True or False for every penguin, with the same row numbers.
The first five are False. None of them is that heavy, and the one with no mass is False too. In all, a hundred and fifteen are True.
If you said one True or False: in plain Python, yes. But here the comparison runs on the whole column at once. It's like NumPy, adding a number to a whole array in one line.
Keep the True rows
So what are all those Trues for? Line six puts keep inside the table's square brackets.
There, a name picks a column. But a column of True and False picks rows.
The new table is called heavy. It has a hundred and fifteen rows, and every column.
Look at its row numbers.
They jump. The rows in between were False, so they were left out.
That's a filter. And df still holds every penguin.
Two conditions
Now, two conditions: over four and a half kilos, and under five. So line five now joins the two comparisons with and.
Will it run?
It stops. "The truth value of a Series is ambiguous."
A Series is pandas' word for one column. The truth value is the one True or False that "and" needs. But "and" gets hundreds of them. Ambiguous means that pandas can't tell which one you mean.
Row by row
The fix is this sign, between the two comparisons. It's called an ampersand, and pandas reads it as "and", row by row.
A row is True only where both are True.
Each comparison goes in its own round brackets. That way, Python finishes both comparisons first... and only then joins them.
Now heavy holds forty-eight penguins, with every column.
Groups
The table holds penguins of three species: three kinds of penguin. Each penguin has its own row. Which kind is the heaviest? Line seven, groupby, puts the rows into groups by their species. Look at how many are in each.
One number for each group
Line eight takes the mass column of each group, and its average: mean.
Before it runs: which kind is the heaviest?
Gentoo. Just over five kilos.
The other two kinds are much lighter, under four kilos.
One number for a whole group is called a summary. Three groups... three numbers.
Every row
So here's what you saw. A table has a name on each column. A comparison gives True or False for every row, and the table keeps the True ones. Two conditions need the ampersand between them.
And groupby, with a summary, gives one number for each group.
Row by row
So a table keeps the rows you want.
And it sums up each group. Now try it on this lesson's page, and take the quiz. Find the island with the heaviest penguins.
You use this lesson in Lab 4: From a table to a first prediction, after The scikit-learn pattern.
Facts last checked on .
