Menu
CoddyTech

Grouping Data

Part of the Data and Plots section of Coddy's Machine Learning journey. Lesson 43 of 60.

Which city sells more? One average over every row cannot say. Split the rows into piles, one per city, then average each pile:

Six shop rows split into three piles by city, Lyon, Nice and Paris, then each pile averaged: Lyon 23.0, Nice 18.0, Paris 38.0

One line does both:

shops = pd.DataFrame({
    "city": ["Lyon", "Paris", "Lyon", "Nice", "Paris", "Lyon"],
    "sales": [20, 35, 26, 18, 41, 23],
})
means = shops.groupby("city")["sales"].mean()
print(means)

This prints:

city
Lyon     23.0
Nice     18.0
Paris    38.0
Name: sales, dtype: float64

groupby("city") makes the piles, ["sales"] picks the column, .mean() averages each pile. .sum(), .min() and .max() work too.

To rank the piles, sort them: means.sort_values(ascending=False).index[0] is Paris, the best seller.

challenge icon

Challenge

Medium

A running club logs every run in runs.csv: runner, distance_km, minutes and climb_m. The starter reads one of the number columns into column.

  1. Print that column's mean for each runner.
  2. Then name the runner with the largest mean, as in the last line below.

For a two-runner club and distance_km:

runner
Ana    6.1
Bo     8.4
Name: distance_km, dtype: float64
Top runner: Bo with 8.4

Try it yourself

import pandas as pd

runs = pd.read_csv("runs.csv")
column = input()

# Write your code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Data and Plots

Practice on your own: Online Python compiler