Tsallaka zuwa abun ciki
Justice Tech School

Group By

groupby splits rows by a key, applies a function to each group and combines the results.

Example
import pandas as pd
import numpy as np
df = pd.DataFrame({'name': ['Ada', 'Bob', 'Cy', 'Di'], 'age': [30, 25, 35, 28], 'city': ['Lagos', 'Accra', 'Lagos', 'Nairobi'], 'score': [88.5, 92.0, 79.5, 85.0]})
print(df.groupby('city')['score'].mean())
print(df.groupby('city').size())
print(df.groupby('city')['age'].max().to_dict())

Result

city
Accra      92.0
Lagos      84.0
Nairobi    85.0
Name: score, dtype: float64
city
Accra      1
Lagos      2
Nairobi    1
dtype: int64
{'Accra': 25, 'Lagos': 35, 'Nairobi': 28}

Exercise

Group by city.

df.("city")

Quiz Test

What does size give?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.