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:
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: float64groupby("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
MediumA 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.
- Print that column's mean for each runner.
- 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.4Try it yourself
import pandas as pd
runs = pd.read_csv("runs.csv")
column = input()
# Write your code below
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Data and Plots
2NumPy Arrays
Creating ArraysShape and SizeRanges of NumbersIndexing and SlicingRecap: Temperature Grid3Array Math
Math on Whole ArraysSummary StatisticsStatistics by AxisBroadcastingBoolean MasksRecap: Exam Scores9Grouping and Cleaning
Counting ValuesGrouping DataSeveral SummariesMissing ValuesRecap: Survey ResultsPractice on your own: Online Python compiler