Module 3 · pandas · Lesson 19 of 66
Groupby
Split rows into groups and summarize each one.
In this lesson · about 12 minutes
- Group rows by a column
- Summarize groups with mean, sum, count and describe
- Pick the column to summarize
groupby gathers rows that share a value, then lets you summarize each group. It's the code version of a spreadsheet's subtotal or pivot. You'll use it on almost every data set: sales per company, pay per year, purchases per browser.
The pattern is: group by a column, pick the column to summarize, then aggregate.
Exercise
Best sale per company
Get the highest Sales value for each company.
Code that runs before yours
import pandas as pd
df = pd.DataFrame({
'Company': ['GOOG', 'GOOG', 'MSFT', 'MSFT', 'FB', 'FB'],
'Person': ['Sam', 'Charlie', 'Amy', 'Vanessa', 'Carl', 'Sarah'],
'Sales': [200, 120, 340, 124, 243, 350],
})Exercise
Total per company
Set totals to the total sales per company, then set top to the name of the company with the highest total.
Code that runs before yours
import pandas as pd
df = pd.DataFrame({
'Company': ['GOOG', 'GOOG', 'MSFT', 'MSFT', 'FB', 'FB'],
'Person': ['Sam', 'Charlie', 'Amy', 'Vanessa', 'Carl', 'Sarah'],
'Sales': [200, 120, 340, 124, 243, 350],
})Check your understanding0 of 1 correct
Quiz score: 0 of 1
Exercises solved: 0 of 2
Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.