Lesson 4 of 6 · about 20 minutes
Grouping and sorting
Grouping
Many questions are about groups: total sales per shop, average score per class, number of pets per animal. groupby() splits a table into groups by the values in a column, runs a summary on each group, and puts the answers together.
import pandas as pd
sales = pd.DataFrame({
"shop": ["North", "South", "North", "East", "South", "North"],
"fruit": ["apple", "apple", "pear", "pear", "pear", "apple"],
"boxes": [12, 7, 9, 4, 10, 15],
})
print(sales.groupby("shop")["boxes"].sum())The output:
shop
East 4
North 36
South 17
Name: boxes, dtype: int64Read it as: group the rows by shop, take the boxes column, and add it up for each group. Swap sum() for mean(), max(), min() or count() to ask a different question. size() counts the rows in each group:
import pandas as pd
sales = pd.DataFrame({
"shop": ["North", "South", "North", "East", "South", "North"],
"boxes": [12, 7, 9, 4, 10, 15],
})
print(sales.groupby("shop").size())
print(sales.groupby("shop")["boxes"].mean())The output:
shop
East 1
North 3
South 2
dtype: int64
shop
East 4.0
North 12.0
South 8.5
Name: boxes, dtype: float64Quick check
What does sales.groupby("shop")["boxes"].max() give you?
Several summaries at once
agg() runs several summaries on each group in one go:
import pandas as pd
sales = pd.DataFrame({
"shop": ["North", "South", "North", "East", "South", "North"],
"boxes": [12, 7, 9, 4, 10, 15],
})
print(sales.groupby("shop")["boxes"].agg(["count", "sum", "max"]))The output:
count sum max
shop
East 1 4 4
North 3 36 15
South 2 17 10Grouping by more than one column
Pass a list of columns to group by every combination of them:
import pandas as pd
sales = pd.DataFrame({
"shop": ["North", "South", "North", "East", "South", "North"],
"fruit": ["apple", "apple", "pear", "pear", "pear", "apple"],
"boxes": [12, 7, 9, 4, 10, 15],
})
totals = sales.groupby(["shop", "fruit"])["boxes"].sum()
print(totals)
print()
print(totals.reset_index())The output:
shop fruit
East pear 4
North apple 27
pear 9
South apple 7
pear 10
Name: boxes, dtype: int64
shop fruit boxes
0 East pear 4
1 North apple 27
2 North pear 9
3 South apple 7
4 South pear 10The result has a two-level index (a MultiIndex). reset_index() turns the index back into ordinary columns, which is usually easier to work with.
Sorting
sort_values() sorts a table by a column. It sorts from smallest to largest unless you pass ascending=False:
import pandas as pd
sales = pd.DataFrame({
"shop": ["North", "South", "North", "East", "South", "North"],
"fruit": ["apple", "apple", "pear", "pear", "pear", "apple"],
"boxes": [12, 7, 9, 4, 10, 15],
})
print(sales.sort_values("boxes", ascending=False))
print()
print(sales.sort_values(["shop", "boxes"]))The output:
shop fruit boxes
5 North apple 15
0 North apple 12
4 South pear 10
2 North pear 9
1 South apple 7
3 East pear 4
shop fruit boxes
3 East pear 4
2 North pear 9
0 North apple 12
5 North apple 15
1 South apple 7
4 South pear 10With a list of columns, pandas sorts by the first and uses the next ones to break ties. sort_index() sorts by the row labels instead.
Grouping and sorting are often used together, for example to find the best shop:
import pandas as pd
sales = pd.DataFrame({
"shop": ["North", "South", "North", "East", "South", "North"],
"boxes": [12, 7, 9, 4, 10, 15],
})
print(sales.groupby("shop")["boxes"].sum().sort_values(ascending=False))The output:
shop
North 36
South 17
East 4
Name: boxes, dtype: int64Quick check
How do you sort df from the highest score to the lowest?
Exercise 1: Average per class
Store the average score of each class in a Series called averages and print it.
Exercise 2: Biggest first
Make a DataFrame called ranked with the cities sorted by population, largest first. Print it.
Exercise 3: The best seller
Find the total sold for each book, then print the title of the book that sold the most in total.
Lesson 4 complete
You finished grouping and sorting and passed every exercise.
What you learned
df.groupby("col")["other"].sum()answers a question for each group.mean(),max(),count()andsize()work too..agg(["count", "sum", "max"])gives several summaries at once.- Group by a list of columns for every combination;
reset_index()turns the index back into columns. sort_values("col", ascending=False)sorts by a column;sort_index()sorts by the row labels.