Module 1, topic 11, week 6, Tuesday
Pandas data cleaning and wrangling
Choosing rows with a condition, missing values, duplicates, types and text, summaries by group, and joining two tables
Lesson notebook
The lesson as a Jupyter notebook: the explanations, every example and the 15 solved problems, ready to run and change.
topic-11-pandas-cleaning-wrangling.ipynb, 60 KB
Practice notebook
The 15 practice problems as one notebook that continues from a setup cell, with a hint and a hidden solution for each.
topic-11-practice.ipynb, 24 KB
Data file: the orders
300 orders of an invented online shop in 2025, the same file as in the last lesson.
orders.csv, 14 KB
Data file: the customers
One row for every customer of the shop: age, gender and the year of joining. Used for joining two tables.
customers.csv, 1 KB
Introduction: cleaning and wrangling data
A beginner-friendly guide to the daily work with tables in pandas. Real data is never ready: values are missing, numbers are stored as text, names are written in three ways, and the answer you need is spread over two files. This guide shows how to choose rows with a condition, how to find and repair missing values, duplicates, wrong types and messy text, how to summarise a table by groups, and how to join two tables. It starts from the simplest examples and gets harder step by step. Then it walks through 15 solved problems from easy to medium-hard. At the end there are practice problems.
You should already know the last lesson: reading a file, head, info, choosing columns, loc and iloc, sorting and making a new column.
The data files. The examples use the same file as the last lesson, orders.csv: 300 orders of a small online shop in 2025. For joining tables there is a second file, customers.csv: one row for every customer. Put both files into the same folder as your notebook.
On this page both files are already there for every example. You can look at them below and in Part 7, and download them from the box at the top.
The data file: orders.csv
300 orders, 8 columns. A cell marked "empty" has no value in the file: pandas shows it as NaN.
Loading the table ...
What you will learn
- 1.Choosing rows with a condition: masks,
&,|,~,isin,between,str.contains - 2.Finding missing values with
isna, removing them withdropna, filling them withfillna - 3.Finding and removing duplicates
- 4.Repairing types:
pd.to_numeric,astype,pd.to_datetime,select_dtypes - 5.Cleaning text with the
.strmethods - 6.Summaries by group:
groupby,agg,pivot_table - 7.Joining two tables with
merge, and stacking tables withconcat - 8.A complete cleaning from the file to the answer
- 9.15 solved problems and practice problems
1Choosing rows with a condition
In the NumPy lesson a condition on an array gave a mask of True and False, and the mask chose the elements. A column of a table works in the same way, and the mask chooses rows.
1.1A condition gives a mask
import pandas as pd
df = pd.read_csv("orders.csv")
expensive = df["price"] > 100
print(expensive.head())
print(expensive.sum())Output
0 False 1 True 2 False 3 False 4 False Name: price, dtype: bool 18
Change it and run: change 100 to 50. How many orders are above 50?
The comparison is done for every row. True counts as 1, so sum counts the rows where the condition holds: 18 orders have a price above 100.
1.2The mask chooses the rows
print(df[df["price"] > 200])Output
date customer city category product price units rating 68 2025-04-19 Aida Sumqayit Tech Smartwatch 249.0 1 4.0 76 2025-05-02 Ramin Sumqayit Tech Smartwatch 249.0 1 NaN 101 2025-06-05 Vusal Ganja Tech Smartwatch 249.0 1 5.0 119 2025-06-21 Konul Quba Tech Smartwatch 224.1 1 3.0 120 2025-06-27 Aysel Baku Tech Smartwatch 249.0 1 5.0 171 2025-08-31 Ramin Sumqayit Tech Smartwatch 224.1 2 3.0 207 2025-10-07 Ilkin Ganja Tech Smartwatch 249.0 1 5.0 265 2025-12-06 Aysel Baku Tech Smartwatch 224.1 1 5.0 277 2025-12-18 Sabina Ganja Tech Smartwatch 249.0 1 3.0 280 2025-12-21 Lala Baku Tech Smartwatch 249.0 1 2.0
Change it and run: print the orders with exactly 5 units.
Read df[df["price"] > 200] as: "the rows of df where the price is above 200". The rows keep their labels.
1.3Conditions with text
shaki = df[df["city"] == "Shaki"]
print(len(shaki))
print(shaki.head(3))Output
10
date customer city category product price units rating
26 2025-02-19 Ruslan Shaki Books Dictionary 29.9 1 4.0
45 2025-03-15 Ruslan Shaki Clothing Jeans 64.9 1 4.0
51 2025-03-20 Ruslan Shaki Tech Power bank 45.0 1 2.0Change it and run: write "shaki" with a small letter. No row is found.
== compares for equality. Text must match exactly: "shaki" with a small letter finds nothing.
1.4Two conditions: &, | and ~
As with NumPy masks: & means "and", | means "or", ~ means "not", and every condition needs its own parentheses.
baku_tech = df[(df["city"] == "Baku") & (df["category"] == "Tech")]
print(len(baku_tech))
cheap_or_many = df[(df["price"] < 8) | (df["units"] == 5)]
print(len(cheap_or_many))
not_baku = df[~(df["city"] == "Baku")]
print(len(not_baku))Output
25 13 172
Change it and run: count the orders of Ganja in the category Books.
1.5One of several values: isin
small_cities = df[df["city"].isin(["Shaki", "Quba"])]
print(len(small_cities))
print(small_cities["city"].value_counts())Output
40 city Quba 30 Shaki 10 Name: count, dtype: int64
Change it and run: add "Lankaran" to the list.
isin takes a list and is True where the value is one of the list. It replaces a long chain of |.
Choose a condition. The mask says True or False for every row.
print(df[df["price"] > 50])
| mask | product | city | price | units | |
|---|---|---|---|---|---|
| 0 | False | Mug | Baku | 8.5 | 2 |
| 1 | True | Jacket | Ganja | 129.0 | 1 |
| 2 | False | Cookbook | Baku | 24.9 | 4 |
| 3 | False | Novel | Shaki | 12.5 | 3 |
| 4 | True | Jeans | Baku | 64.9 | 1 |
| 5 | True | Keyboard | Ganja | 59.9 | 2 |
3 of 6 rows are chosen: the rows where the mask is True. The other rows are left out, and the chosen rows keep their labels.
1.6Between two numbers: between
middle = df[df["price"].between(50, 100)]
print(len(middle))
print(middle["price"].min(), middle["price"].max())Output
83 51.92 99.9
Change it and run: count the prices from 10 to 20.
between(50, 100) includes both ends. It means the same as (df["price"] >= 50) & (df["price"] <= 100).
1.7A piece of text: str.contains
books = df[df["product"].str.contains("book")]
print(books["product"].unique().tolist())
print(len(books))Output
['Cookbook', 'Textbook'] 33
Change it and run: look for "mat" instead of "book".
str.contains("book") is True where the text has "book" somewhere inside: Cookbook and Textbook.
1.8Rows by a condition, columns by name: loc
print(df.loc[df["units"] == 5, ["customer", "product", "units"]])Output
customer product units 31 Leyla Cookbook 5 44 Javid Novel 5 55 Zahra Novel 5 58 Anar Yoga mat 5 93 Lala Football 5 264 Javid Cookbook 5
Change it and run: show the columns date and city of the same rows.
A mask can stand in the row place of loc. After the comma come the columns you want to see.
1.9Summaries of the chosen rows
baku = df[df["city"] == "Baku"]
ganja = df[df["city"] == "Ganja"]
print(len(baku), round(baku["price"].mean(), 2))
print(len(ganja), round(ganja["price"].mean(), 2))Output
128 48.84 54 54.11
Change it and run: do the same for Sumqayit.
Filtering first and then summarising answers questions like "what is the average price in Baku?".
1.10Changing values where a condition holds
df["size"] = "small"
df.loc[df["units"] >= 3, "size"] = "large"
print(df[["product", "units", "size"]].head(4))
print(df["size"].value_counts())Output
product units size 0 Mug 2 small 1 Jacket 1 small 2 Cookbook 4 large 3 Cookbook 2 small size small 240 large 60 Name: count, dtype: int64
Change it and run: call the orders with 4 or more units "large".
df.loc[mask, column] = value changes only the rows where the mask is True.
| You write | You get |
|---|---|
df["price"] > 100 | a mask: True or False for every row |
df[df["price"] > 100] | the rows where the condition holds |
(a) & (b), (a) | (b), ~(a) | and, or, not |
df["city"].isin(["Shaki", "Quba"]) | the value is one of the list |
df["price"].between(50, 100) | from 50 to 100, both included |
df["product"].str.contains("book") | the text has this piece inside |
df.loc[mask, ["customer", "units"]] | the chosen rows, only these columns |
df.loc[mask, "size"] = "large" | changes the chosen rows |
Try it yourself
Show a hint
df[df["price"] > 200].Show the solution
import pandas as pd
df = pd.read_csv("orders.csv")
print(df[df["price"] > 200])Output
date customer city category product price units rating 68 2025-04-19 Aida Sumqayit Tech Smartwatch 249.0 1 4.0 76 2025-05-02 Ramin Sumqayit Tech Smartwatch 249.0 1 NaN 101 2025-06-05 Vusal Ganja Tech Smartwatch 249.0 1 5.0 119 2025-06-21 Konul Quba Tech Smartwatch 224.1 1 3.0 120 2025-06-27 Aysel Baku Tech Smartwatch 249.0 1 5.0 171 2025-08-31 Ramin Sumqayit Tech Smartwatch 224.1 2 3.0 207 2025-10-07 Ilkin Ganja Tech Smartwatch 249.0 1 5.0 265 2025-12-06 Aysel Baku Tech Smartwatch 224.1 1 5.0 277 2025-12-18 Sabina Ganja Tech Smartwatch 249.0 1 3.0 280 2025-12-21 Lala Baku Tech Smartwatch 249.0 1 2.0
2Missing values
2.1Finding them
import pandas as pd
df = pd.read_csv("orders.csv")
print(df.isna().sum())Output
date 0 customer 0 city 8 category 0 product 0 price 0 units 0 rating 36 dtype: int64
Change it and run: print df.notna().sum(): the number of values that are there.
isna() gives True where a value is missing, and sum counts the True values of every column. Two columns have gaps: city (8) and rating (36).
2.2The rows with a missing value
print(df[df["city"].isna()])
print(df["rating"].notna().sum())Output
date customer city category product price units rating 62 2025-04-12 Narmin NaN Clothing Jeans 58.41 1 3.0 91 2025-05-20 Ramin NaN Clothing Jacket 103.20 1 5.0 99 2025-06-04 Vusal NaN Home Pillow 22.00 1 5.0 115 2025-06-17 Nigar NaN Tech Keyboard 59.90 1 NaN 132 2025-07-13 Emin NaN Home Desk lamp 34.90 1 4.0 199 2025-09-30 Nazrin NaN Clothing T-shirt 19.90 4 4.0 244 2025-11-15 Ilkin NaN Home Pillow 19.80 1 NaN 253 2025-11-24 Ramin NaN Sports Dumbbells 54.90 1 5.0 264
Change it and run: print the rows where the rating is missing: only the first 5.
isna() is a mask like any other, so it chooses rows. notna() is the opposite: 264 orders have a rating.
2.3Why not == NaN?
print(len(df[df["rating"] == float("nan")]))
print(len(df[df["rating"].isna()]))Output
0 36
A missing value is not equal to anything, not even to another missing value. A comparison with == never finds it. Always use isna().
2.4Way 1: remove the rows, dropna
print(df.shape)
print(df.dropna().shape)
print(df.dropna(subset=["city"]).shape)Output
(300, 8) (258, 8) (292, 8)
Change it and run: check only the column rating: df.dropna(subset=["rating"]).
dropna() removes every row that has a gap anywhere: 42 rows are lost. With subset only the named columns are checked: only the 8 rows without a city go. dropna gives a new table, as most methods do.
2.5Way 2: fill the gaps, fillna
A missing text can get a clear word:
df["city"] = df["city"].fillna("Unknown")
print(df["city"].value_counts())Output
city Baku 128 Ganja 54 Sumqayit 48 Quba 30 Lankaran 22 Shaki 10 Unknown 8 Name: count, dtype: int64
Change it and run: fill with "No city" instead.
fillna gives a new column, so the result is stored back into df["city"]. Now all 300 orders are counted.
A missing number is often filled with the median or the mean of the column:
df = pd.read_csv("orders.csv")
middle = df["rating"].median()
print(middle)
df["rating"] = df["rating"].fillna(middle)
print(df["rating"].isna().sum())
print(round(df["rating"].mean(), 2))Output
4.0 0 4.06
Change it and run: fill with the mean instead of the median. What is the mean of the column after it?
The median of the ratings is 4.0, and the 36 gaps get this value. No gap is left.
rating
4 rows, one gap
dropna()
The row is removed: 3 rows
fillna(4.0)
The gap gets a value: 4 rows
2.6Remove or fill?
| Situation | A good choice |
|---|---|
| Few rows have gaps, and you have many rows | remove them: dropna(subset=[...]) |
| The column is text | fill with a word: fillna("Unknown") |
| The column is a number | fill with the median (or the mean) |
| The gap itself is the information ("gave no rating") | keep it, and remember that summaries skip it |
| Most values of a column are missing | remove the column: drop(columns=[...]) |
There is no rule that is always right. Filling changes the data, so say what you did.
Try it yourself
Show a hint
df.isna() marks the gaps, and .sum() counts them for every column.Show the solution
import pandas as pd
df = pd.read_csv("orders.csv")
print(df.isna().sum())Output
date 0 customer 0 city 8 category 0 product 0 price 0 units 0 rating 36 dtype: int64
3Duplicates
Sometimes the same row is in a file twice, for example because a form was sent two times.
3.1Finding and removing them
import pandas as pd
visits = pd.DataFrame({
"name": ["Aylin", "Murad", "Aylin", "Leyla", "Murad"],
"city": ["Baku", "Ganja", "Baku", "Baku", "Shaki"],
})
print(visits.duplicated())
print(visits.duplicated().sum())
print(visits.drop_duplicates())Output
0 False
1 False
2 True
3 False
4 False
dtype: bool
1
name city
0 Aylin Baku
1 Murad Ganja
3 Leyla Baku
4 Murad ShakiChange it and run: change the last city from Shaki to Ganja. Now there are two duplicates.
duplicated() marks a row as True when the same row appeared before it. Row 2 repeats row 0. Row 4 is not a duplicate: the name is the same, but the city is different. drop_duplicates() keeps the first of the equal rows.
3.2Duplicates in some columns only
print(visits.drop_duplicates(subset=["name"]))Output
name city 0 Aylin Baku 1 Murad Ganja 3 Leyla Baku
Change it and run: compare only the column city.
With subset only these columns are compared: every name stays once, with its first row.
3.3The orders
df = pd.read_csv("orders.csv")
print(df.duplicated().sum())
first_orders = df.drop_duplicates(subset=["customer"])
print(len(first_orders))
print(first_orders[["date", "customer", "product"]].head(3))Output
0
40
date customer product
0 2025-01-01 Nigar Mug
1 2025-01-03 Ziya Jacket
2 2025-01-11 Anar CookbookChange it and run: keep the first order of every city instead.
The file has no repeated rows. drop_duplicates(subset=["customer"]) has another use here: it keeps the first order of each of the 40 customers.
Try it yourself
items are duplicates. Then print the table without them.Show a hint
items.duplicated().sum() counts them, and items.drop_duplicates() removes them. The Mug for 9.0 is not a duplicate: its price is different.Show the solution
import pandas as pd
items = pd.DataFrame({
"product": ["Mug", "Novel", "Mug", "Mug", "Jeans"],
"price": [8.5, 12.5, 8.5, 9.0, 64.9],
})
print(items.duplicated().sum())
print(items.drop_duplicates())Output
1 product price 0 Mug 8.5 1 Novel 12.5 3 Mug 9.0 4 Jeans 64.9
4Repairing types
A column of numbers that was read as text cannot be added up or compared. The type is the first thing to check, with dtypes or info().
4.1A small messy table
This table is like many real files: typed by hand, with mistakes.
import pandas as pd
raw = pd.DataFrame({
"name": [" aylin", "MURAD ", "Leyla", "leyla", "Kamran"],
"city": ["baku", "Baku ", "GANJA", "Ganja", "baku"],
"age": ["20", "25", "twenty-two", "22", "30"],
"paid": ["15.5 AZN", "20 AZN", "n/a", "18.0 AZN", "25.5 AZN"],
})
print(raw)
print(raw.dtypes)Output
name city age paid 0 aylin baku 20 15.5 AZN 1 MURAD Baku 25 20 AZN 2 Leyla GANJA twenty-two n/a 3 leyla Ganja 22 18.0 AZN 4 Kamran baku 30 25.5 AZN name str city str age str paid str dtype: object
Every column is text, also age. This part repairs age, and Part 5 repairs the text columns.
4.2pd.to_numeric
raw = pd.DataFrame({
"name": [" aylin", "MURAD ", "Leyla", "leyla", "Kamran"],
"age": ["20", "25", "twenty-two", "22", "30"],
})
raw["age"] = pd.to_numeric(raw["age"])Error
ValueError: Unable to parse string "twenty-two" at position 2
One value is not a number, so the conversion stops. With errors="coerce" such values become missing values instead:
raw = pd.DataFrame({
"name": [" aylin", "MURAD ", "Leyla", "leyla", "Kamran"],
"age": ["20", "25", "twenty-two", "22", "30"],
})
raw["age"] = pd.to_numeric(raw["age"], errors="coerce")
print(raw)
print(raw["age"].dtype)
print(raw["age"].mean())Output
name age 0 aylin 20.0 1 MURAD 25.0 2 Leyla NaN 3 leyla 22.0 4 Kamran 30.0 float64 24.25
Change it and run: change "twenty-two" to "22". No gap is left.
Now age is a number column with one gap, and the mean can be calculated. The gap is a job for Part 2.
4.3astype: when every value fits
raw = pd.DataFrame({"age": ["20", "25", "twenty-two", "22", "30"]})
raw["age"] = pd.to_numeric(raw["age"], errors="coerce")
raw["age"] = raw["age"].fillna(raw["age"].median())
raw["age"] = raw["age"].astype(int)
print(raw["age"].tolist())Output
[20, 25, 23, 22, 30]
Change it and run: fill the gap with 0 instead of the median.
A column with a gap is stored as decimals. After the gap is filled, astype(int) makes whole numbers again. astype is strict: it works only when every value can be converted.
4.4Dates: pd.to_datetime
df = pd.read_csv("orders.csv")
df["date"] = pd.to_datetime(df["date"])
df["month"] = df["date"].dt.month
df["weekday"] = df["date"].dt.day_name()
print(df[["date", "month", "weekday"]].head(3))
print(df["month"].value_counts().head(3))Output
date month weekday 0 2025-01-01 1 Wednesday 1 2025-01-03 1 Friday 2 2025-01-11 1 Saturday month 12 40 11 34 9 28 Name: count, dtype: int64
Change it and run: print the three weekdays with the most orders.
pd.to_datetime turns text into real dates. Real dates have the .dt tools: dt.month, dt.day, dt.year, dt.day_name(). With a month column you can count and group by month: December was the busiest month.
4.5Columns of one kind: select_dtypes
df = pd.read_csv("orders.csv")
numbers = df.select_dtypes(include="number")
print(numbers.columns.tolist())
print(numbers.mean().round(2))
others = df.select_dtypes(exclude="number")
print(others.columns.tolist())Output
['price', 'units', 'rating'] price 50.64 units 1.73 rating 4.06 dtype: float64 ['date', 'customer', 'city', 'category', 'product']
Change it and run: print the largest value of every number column.
select_dtypes(include="number") keeps only the number columns, exclude="number" keeps the rest. It is handy before a calculation that makes sense only for numbers.
| You write | What it does |
|---|---|
df.dtypes | shows the type of every column |
pd.to_numeric(column, errors="coerce") | text to numbers; what is not a number becomes missing |
column.astype(int) | changes the type; every value must fit |
pd.to_datetime(column) | text to real dates |
column.dt.month, column.dt.day_name() | parts of a date |
df.select_dtypes(include="number") | only the number columns |
Try it yourself
scores into numbers, so that what is not a number becomes a missing value. Print the numbers as a list, then their mean.Show a hint
pd.to_numeric(scores, errors="coerce"). Print the result with .tolist(), then .mean(). The mean skips the gap.Show the solution
import pandas as pd
scores = pd.Series(["85", "92", "absent", "78"])
numbers = pd.to_numeric(scores, errors="coerce")
print(numbers.tolist())
print(numbers.mean())Output
[85.0, 92.0, nan, 78.0] 85.0
5Cleaning text
For a computer, "baku", "Baku " and "Baku" are three different cities. Text columns have their own tools, reached with .str.
5.1The problem
import pandas as pd
raw = pd.DataFrame({
"name": [" aylin", "MURAD ", "Leyla", "leyla", "Kamran"],
"city": ["baku", "Baku ", "GANJA", "Ganja", "baku"],
})
print(raw["city"].value_counts())Output
city baku 2 Baku 1 GANJA 1 Ganja 1 Name: count, dtype: int64
Two cities are counted as four.
5.2strip, lower, upper, title
raw["city"] = raw["city"].str.strip().str.title()
raw["name"] = raw["name"].str.strip().str.title()
print(raw)
print(raw["city"].value_counts())Output
name city 0 Aylin Baku 1 Murad Baku 2 Leyla Ganja 3 Leyla Ganja 4 Kamran Baku city Baku 3 Ganja 2 Name: count, dtype: int64
Change it and run: use .str.upper() instead of .str.title().
str.strip() removes the spaces at both ends, and str.title() writes every word with a capital first letter. The methods are the string methods you know, done for the whole column. Now the cities are counted correctly, and the two rows of Leyla have become equal, so drop_duplicates could find them.
5.3str.replace, then a number
raw = pd.DataFrame({"paid": ["15.5 AZN", "20 AZN", "n/a", "18.0 AZN", "25.5 AZN"]})
raw["paid"] = raw["paid"].str.replace(" AZN", "")
print(raw["paid"].tolist())
raw["paid"] = pd.to_numeric(raw["paid"], errors="coerce")
print(raw["paid"].tolist())
print(raw["paid"].sum())Output
['15.5', '20', 'n/a', '18.0', '25.5'] [15.5, 20.0, nan, 18.0, 25.5] 79.0
Change it and run: change "n/a" to "12 AZN". The sum grows.
First the text " AZN" is removed, then to_numeric makes numbers, and "n/a" becomes a missing value. Cleaning is often a chain of such small steps.
| You write | What it does |
|---|---|
column.str.strip() | removes spaces at both ends |
column.str.lower(), .str.upper(), .str.title() | changes the letters |
column.str.replace(" AZN", "") | replaces a piece of text |
column.str.contains("book") | True where the piece is inside |
column.str.len() | the length of every text |
Try it yourself
Show a hint
paid.str.replace(" AZN", "") removes the text, then pd.to_numeric(..., errors="coerce") makes numbers. "none" becomes a missing value, and the sum skips it.Show the solution
import pandas as pd
paid = pd.Series(["10 AZN", "7.5 AZN", "none", "12 AZN"])
paid = paid.str.replace(" AZN", "")
paid = pd.to_numeric(paid, errors="coerce")
print(paid.sum())Output
29.5
6Summaries by group
"The average price" is one number. "The average price of every category" needs groups. groupby does three things: it splits the rows into groups, calculates a summary for every group, and puts the results together.
df.groupby("category")["price"].mean()
1. The rows
2. Split into groups
3. One mean for every group
6.1One column, one summary
import pandas as pd
df = pd.read_csv("orders.csv")
print(df.groupby("category")["price"].mean())Output
category Books 25.435811 Clothing 70.591111 Home 26.793929 Sports 38.992292 Tech 90.078382 Name: price, dtype: float64
Change it and run: group by city instead of category.
Read it from left to right: group by category, take the column price, calculate the mean. The result is a Series, and the groups are its labels.
6.2Other summaries
print(df.groupby("city")["units"].sum())
print(df.groupby("category")["rating"].count())
print(df.groupby("category").size())Output
city Baku 216 Ganja 97 Lankaran 47 Quba 50 Shaki 14 Sumqayit 85 Name: units, dtype: int64 category Books 67 Clothing 48 Home 48 Sports 41 Tech 60 Name: rating, dtype: int64 category Books 74 Clothing 54 Home 56 Sports 48 Tech 68 dtype: int64
Change it and run: print the largest price of every category.
sum, mean, median, min, max and count all work. count counts the values that are not missing, and size counts all rows of a group. Notice the first result: the 8 orders without a city are in no group.
6.3Group, then sort
df["total"] = df["price"] * df["units"]
revenue = df.groupby("category")["total"].sum()
print(revenue.sort_values(ascending=False))Output
category Tech 7424.00 Clothing 4846.81 Books 3629.74 Sports 3297.39 Home 2737.28 Name: total, dtype: float64
Change it and run: sort from the smallest to the largest.
The money of every category, the largest first. A new column, a group and a sort: this chain answers most business questions.
6.4Several summaries at once: agg
df = pd.read_csv("orders.csv")
print(df.groupby("category")["price"].agg(["count", "mean", "max"]).round(2))Output
count mean max category Books 74 25.44 39.9 Clothing 54 70.59 129.0 Home 56 26.79 49.9 Sports 48 38.99 54.9 Tech 68 90.08 249.0
Change it and run: add "min" to the list.
A list of names gives one column for every summary.
6.5Different columns, different summaries
df["total"] = df["price"] * df["units"]
report = df.groupby("city").agg({"units": "sum", "total": "sum", "rating": "mean"})
print(report.round(2))Output
units total rating city Baku 216 9093.10 4.03 Ganja 97 4213.20 4.12 Lankaran 47 1358.15 4.11 Quba 50 1986.82 4.31 Shaki 14 649.64 3.50 Sumqayit 85 4201.60 4.00
Change it and run: use "max" for the rating.
A dictionary says which summary to use for which column.
6.6Groups by two columns
df = pd.read_csv("orders.csv")
counts = df.groupby(["city", "category"]).size()
print(counts.head(7))
print(counts["Baku"]["Tech"])Output
city category
Baku Books 29
Clothing 28
Home 21
Sports 25
Tech 25
Ganja Books 17
Clothing 10
dtype: int64
25Change it and run: print the number of orders in Ganja in the category Books.
Every pair of city and category is one group. The result has two levels of labels.
6.7Back to a normal table: reset_index
table = df.groupby(["city", "category"]).size().reset_index(name="orders")
print(table.head(4))
print(table.sort_values("orders", ascending=False).head(2))Output
city category orders 0 Baku Books 29 1 Baku Clothing 28 2 Baku Home 21 3 Baku Sports 25 city category orders 0 Baku Books 29 1 Baku Clothing 28
Change it and run: show the three pairs with the fewest orders.
reset_index turns the group labels into normal columns, so the result can be sorted, filtered and saved like any table.
6.8Groups by month
df["total"] = df["price"] * df["units"]
df["month"] = pd.to_datetime(df["date"]).dt.month
monthly = df.groupby("month")["total"].agg(["count", "sum"])
print(monthly.round(2))Output
count sum month 1 18 1118.03 2 16 1085.53 3 22 1473.77 4 20 1384.73 5 22 1770.02 6 24 2268.12 7 26 1752.02 8 24 1938.49 9 28 1596.42 10 26 2119.20 11 34 1917.28 12 40 3511.61
Change it and run: add "mean" to the list of summaries.
The number of orders and the money of every month. The end of the year is the strongest.
6.9A table of two groups: pivot_table
df = pd.read_csv("orders.csv")
table = df.pivot_table(index="city", columns="category", values="units", aggfunc="sum")
print(table)Output
category Books Clothing Home Sports Tech city Baku 53.0 39.0 39.0 49.0 36.0 Ganja 39.0 12.0 15.0 18.0 13.0 Lankaran 20.0 5.0 15.0 6.0 1.0 Quba 9.0 8.0 20.0 3.0 10.0 Shaki 5.0 4.0 NaN 2.0 3.0 Sumqayit 23.0 7.0 21.0 9.0 25.0
Change it and run: put the average price into the cells: values="price", aggfunc="mean", and round to 1 decimal.
pivot_table puts one group into the rows and another into the columns. Here every cell is the number of units sold in that city and category.
6.10Filtering the groups
orders = df.groupby("customer").size()
loyal = orders[orders >= 15]
print(loyal.sort_values(ascending=False))Output
customer Ramin 28 Murad 24 Aylin 18 Konul 17 dtype: int64
Change it and run: show the customers with at least 10 orders.
The result of a groupby is a Series, so a condition filters it like any other Series: the customers with at least 15 orders.
| You write | You get |
|---|---|
df.groupby("category")["price"].mean() | the mean price of every category |
df.groupby("city").size() | the number of rows of every city |
.agg(["count", "mean", "max"]) | several summaries at once |
.agg({"units": "sum", "rating": "mean"}) | a summary for each column |
df.groupby(["city", "category"]) | groups by two columns |
.reset_index() | the group labels become normal columns |
df.pivot_table(index=, columns=, values=, aggfunc=) | one group in the rows, one in the columns |
Try it yourself
Show a hint
agg gives each column its own summary: df.groupby("city").agg({"units": "sum", "price": "mean"}).Show the solution
import pandas as pd
df = pd.read_csv("orders.csv")
report = df.groupby("city").agg({"units": "sum", "price": "mean"})
print(report.round(2))Output
units price city Baku 216 48.84 Ganja 97 54.11 Lankaran 47 34.94 Quba 50 49.91 Shaki 14 56.50 Sumqayit 85 58.64
7Joining tables
Data about one thing often lives in two files. The orders say who bought something. How old the customer is stands in another table. merge joins two tables by a column that both have: the key.
7.1Two small tables
import pandas as pd
sales = pd.DataFrame({
"product": ["Mug", "Novel", "Mug", "Jacket"],
"units": [2, 1, 3, 1],
})
prices = pd.DataFrame({
"product": ["Mug", "Novel", "Pillow"],
"price": [8.5, 12.5, 22.0],
})
print(sales.merge(prices, on="product"))Output
product units price 0 Mug 2 8.5 1 Novel 1 12.5 2 Mug 3 8.5
Change it and run: add "Jacket" with the price 129.0 to prices. The fourth row appears.
For every row of sales, pandas looks up the row of prices with the same product and puts the two side by side. Mug appears twice in sales, so its price is used twice.
Look at what is missing: Jacket has no price, and Pillow was never sold. Rows without a partner are left out. This is called an inner join.
7.2Keeping all rows of the left table: how="left"
print(sales.merge(prices, on="product", how="left"))Output
product units price 0 Mug 2 8.5 1 Novel 1 12.5 2 Mug 3 8.5 3 Jacket 1 NaN
Change it and run: use how="outer". Pillow appears too.
With how="left" every row of the left table stays. Where no partner exists, the new columns get a missing value: the Jacket has no price.
| how= | Which rows are kept |
|---|---|
"inner" (the default) | only rows with a partner in both tables |
"left" | all rows of the left table |
"right" | all rows of the right table |
"outer" | all rows of both tables |
In practice "left" is the most used: your main table keeps all its rows, and you see what could not be matched.
Choose the kind of join and see which rows stay.
print(sales.merge(prices, on="product", how="inner"))
sales
| product | units |
|---|---|
| Mug | 2 |
| Novel | 1 |
| Mug | 3 |
| Jacket | 1 |
prices
| product | price |
|---|---|
| Mug | 8.5 |
| Novel | 12.5 |
| Pillow | 22.0 |
the result
| product | units | price |
|---|---|---|
| Mug | 2 | 8.5 |
| Novel | 1 | 12.5 |
| Mug | 3 | 8.5 |
3 rows. Only the products that are in both tables stay. Jacket (no price) and Pillow (never sold) are left out.
7.3The second file: customers.csv
customers = pd.read_csv("customers.csv")
print(customers.head())
print(customers.shape)Output
customer age gender joined 0 Aylin 46 F 2025 1 Murad 53 M 2025 2 Leyla 47 F 2023 3 Kamran 50 M 2025 4 Nigar 55 F 2022 (40, 4)
| Column | Meaning |
|---|---|
customer | the first name, as in orders.csv |
age | the age in years |
gender | F or M |
joined | the year the customer registered |
The data file: customers.csv
40 customers, 4 columns. A cell marked "empty" has no value in the file: pandas shows it as NaN.
Loading the table ...
7.4Orders with their customers
df = pd.read_csv("orders.csv")
customers = pd.read_csv("customers.csv")
full = df.merge(customers, on="customer", how="left")
print(full.shape)
print(full[["date", "customer", "product", "age", "gender"]].head(4))Output
(300, 11)
date customer product age gender
0 2025-01-01 Nigar Mug 55.0 F
1 2025-01-03 Ziya Jacket 23.0 M
2 2025-01-11 Anar Cookbook 21.0 M
3 2025-01-13 Gunel Cookbook 29.0 FChange it and run: show the column joined too.
Still 300 rows, now with 11 columns. Each order has the age, the gender and the year of its customer.
7.5Always check what did not match
print(full["age"].isna().sum())
print(full[full["age"].isna()]["customer"].unique().tolist())
inner = df.merge(customers, on="customer")
print(len(inner))Output
3 ['Samir', 'Tural'] 297
Three orders belong to customers who are not in customers.csv. A left join shows them as gaps. An inner join would silently lose these three orders.
7.6Using the joined table
full["total"] = full["price"] * full["units"]
print(full.groupby("gender")["total"].agg(["count", "sum"]).round(2))
print(len(full[full["age"] < 30]))Output
count sum gender F 131 9913.52 M 166 11811.05 85
Change it and run: count the orders of customers who are 50 or older.
After the join, the new columns work like all others: grouping by gender, filtering by age.
7.7Keys with different names
When the key has another name in the second table, name both: orders.merge(people, left_on="customer", right_on="name").
7.8Stacking tables: concat
merge puts tables side by side. concat puts tables with the same columns under each other, for example the files of two months:
january = pd.DataFrame({"product": ["Mug", "Novel"], "units": [2, 1]})
february = pd.DataFrame({"product": ["Jacket", "Mug"], "units": [1, 4]})
both = pd.concat([january, february], ignore_index=True)
print(both)Output
product units 0 Mug 2 1 Novel 1 2 Jacket 1 3 Mug 4
Change it and run: remove ignore_index=True and look at the row labels.
ignore_index=True numbers the rows again from 0.
| You write | What it does |
|---|---|
a.merge(b, on="key") | joins by a column; keeps rows with a partner in both tables |
a.merge(b, on="key", how="left") | keeps all rows of a |
a.merge(b, left_on="x", right_on="y") | the key has different names |
pd.concat([a, b], ignore_index=True) | puts b under a |
Try it yourself
students with cities so that all three students stay. Print the result, then how many students have no city.Show a hint
students.merge(cities, on="name", how="left"). The gaps are counted with result["city"].isna().sum().Show the solution
import pandas as pd
students = pd.DataFrame({"name": ["Aylin", "Murad", "Leyla"], "grade": [85, 92, 78]})
cities = pd.DataFrame({"name": ["Aylin", "Leyla", "Kamran"], "city": ["Baku", "Ganja", "Shaki"]})
result = students.merge(cities, on="name", how="left")
print(result)
print(result["city"].isna().sum())Output
name grade city 0 Aylin 85 Baku 1 Murad 92 NaN 2 Leyla 78 Ganja 1
8From the file to the answer
A real task uses all steps together. The question: which category earns the most money in each city, and how do customers under 30 rate their orders?
8.1Step 1: read, look and clean
import pandas as pd
df = pd.read_csv("orders.csv")
print(df.isna().sum().sum())
print(df.duplicated().sum())
df["city"] = df["city"].fillna("Unknown")
df["date"] = pd.to_datetime(df["date"])
df["total"] = df["price"] * df["units"]
print(df.isna().sum().sum())
print(df.dtypes["date"])Output
44 0 36 datetime64[us]
44 gaps and no duplicates. The city gets the word "Unknown". The ratings stay as they are: a missing rating is information, and summaries skip it. The date becomes a real date, and every order gets its total.
8.2Step 2: group
df = pd.read_csv("orders.csv")
df["city"] = df["city"].fillna("Unknown")
df["total"] = df["price"] * df["units"]
money = df.pivot_table(index="city", columns="category", values="total", aggfunc="sum")
print(money.round(0))
print(money.idxmax(axis=1))Output
category Books Clothing Home Sports Tech city Baku 1292.0 2408.0 901.0 1964.0 2528.0 Ganja 935.0 879.0 399.0 639.0 1361.0 Lankaran 468.0 209.0 443.0 166.0 72.0 Quba 245.0 388.0 401.0 150.0 802.0 Shaki 137.0 125.0 NaN 63.0 325.0 Sumqayit 552.0 597.0 518.0 260.0 2275.0 Unknown NaN 241.0 77.0 55.0 60.0 city Baku Tech Ganja Tech Lankaran Books Quba Tech Shaki Tech Sumqayit Tech Unknown Clothing dtype: str
Change it and run: put the number of orders into the cells: values="price", aggfunc="count".
idxmax(axis=1) gives, for every row, the label of the column with the largest value: the strongest category of every city.
8.3Step 3: join and filter
df = pd.read_csv("orders.csv")
customers = pd.read_csv("customers.csv")
full = df.merge(customers, on="customer", how="left")
young = full[full["age"] < 30]
older = full[full["age"] >= 30]
print(len(young), round(young["rating"].mean(), 2))
print(len(older), round(older["rating"].mean(), 2))Output
85 4.15 212 4.02
Change it and run: use 40 instead of 30 as the limit.
The order of the work is almost always the same: look, clean, add columns, join, filter, group.
Try it yourself
Show a hint
.copy()), add a column total, group by product and sum total. .idxmax() is the name and .max() the money.Show the solution
import pandas as pd
df = pd.read_csv("orders.csv")
baku = df[df["city"] == "Baku"].copy()
baku["total"] = baku["price"] * baku["units"]
money = baku.groupby("product")["total"].sum()
print(money.idxmax())
print(round(money.max(), 2))Output
Sneakers 969.03
9Common mistakes
The red text is the real message Python shows. Where there is no message, the program runs but does the wrong thing: the comment shows what it prints.
and / or between conditions
Wrong
import pandas as pd
df = pd.read_csv("orders.csv")
print(df[(df["price"] > 100) and (df["units"] > 1)])ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Right
import pandas as pd
df = pd.read_csv("orders.csv")
print(len(df[(df["price"] > 100) & (df["units"] > 1)]))
# prints: 1ValueError: the truth value of a Series is ambiguous. Use & and |.
No parentheses around the conditions
Wrong
import pandas as pd
df = pd.read_csv("orders.csv")
print(df[df["price"] > 100 & df["units"] > 1])ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Right
import pandas as pd
df = pd.read_csv("orders.csv")
print(len(df[(df["price"] > 100) & (df["units"] > 1)]))
# prints: 1ValueError. Write (df["price"] > 100) & (df["units"] > 1).
One = in a condition
Wrong
import pandas as pd
df = pd.read_csv("orders.csv")
df["city"] = "Baku"
print(df["city"].nunique())
# prints: 1Right
import pandas as pd
df = pd.read_csv("orders.csv")
print(len(df[df["city"] == "Baku"]))
# prints: 128The whole column is overwritten. == compares.
== NaN to find missing values
Wrong
import pandas as pd
df = pd.read_csv("orders.csv")
print(len(df[df["rating"] == float("nan")]))
# prints: 0Right
import pandas as pd
df = pd.read_csv("orders.csv")
print(len(df[df["rating"].isna()]))
# prints: 36Nothing is found. Use isna().
fillna without storing the result
Wrong
import pandas as pd
df = pd.read_csv("orders.csv")
df["city"].fillna("Unknown")
print(df["city"].isna().sum())
# prints: 8Right
import pandas as pd
df = pd.read_csv("orders.csv")
df["city"] = df["city"].fillna("Unknown")
print(df["city"].isna().sum())
# prints: 0The gaps are still there. Write df["city"] = df["city"].fillna("Unknown").
isin("Baku") with a text
Wrong
import pandas as pd
df = pd.read_csv("orders.csv")
print(df[df["city"].isin("Baku")])TypeError: only list-like objects are allowed to be passed to isin(), you passed a `str`
Right
import pandas as pd
df = pd.read_csv("orders.csv")
print(len(df[df["city"].isin(["Baku"])]))
# prints: 128TypeError. isin takes a list: isin(["Baku"]).
pd.to_numeric on a column with wrong values
Wrong
import pandas as pd ages = pd.Series(["20", "twenty"]) print(pd.to_numeric(ages).tolist())
ValueError: Unable to parse string "twenty" at position 1
Right
import pandas as pd ages = pd.Series(["20", "twenty"]) print(pd.to_numeric(ages, errors="coerce").tolist()) # prints: [20.0, nan]
ValueError. With errors="coerce" the wrong values become missing values.
Text that is not cleaned before counting
Wrong
import pandas as pd cities = pd.Series(["baku", "Baku ", "Baku"]) print(cities.nunique()) # prints: 3
Right
import pandas as pd cities = pd.Series(["baku", "Baku ", "Baku"]) print(cities.str.strip().str.title().nunique()) # prints: 1
"baku" and "Baku " are different values. Use str.strip().str.title() first.
The mean of a text column in a groupby
Wrong
import pandas as pd
df = pd.read_csv("orders.csv")
print(df.groupby("city").mean())TypeError: dtype 'str' does not support operation 'mean'
Right
import pandas as pd
df = pd.read_csv("orders.csv")
print(df.groupby("city")["price"].mean().round(2).tolist())
# prints: [48.84, 54.11, 34.94, 49.91, 56.5, 58.64]TypeError. Choose the column first: groupby("city")["price"].mean().
A wrong key name in merge
Wrong
import pandas as pd
df = pd.read_csv("orders.csv")
customers = pd.read_csv("customers.csv")
full = df.merge(customers, on="name")KeyError: 'name'
Right
import pandas as pd
df = pd.read_csv("orders.csv")
customers = pd.read_csv("customers.csv")
full = df.merge(customers, on="customer")
print(full.shape)
# prints: (297, 11)KeyError. Check columns of both tables.
An inner join that loses rows
Wrong
import pandas as pd
df = pd.read_csv("orders.csv")
customers = pd.read_csv("customers.csv")
print(len(df.merge(customers, on="customer")))
# prints: 297Right
import pandas as pd
df = pd.read_csv("orders.csv")
customers = pd.read_csv("customers.csv")
print(len(df.merge(customers, on="customer", how="left")))
# prints: 300Fewer rows than before, without a message. Use how="left", then count the gaps.
and between two conditions:
import pandas as pd
df = pd.read_csv("orders.csv")
print(df[(df["price"] > 100) and (df["units"] > 1)])Error
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Conditions without parentheses:
import pandas as pd
df = pd.read_csv("orders.csv")
print(df[df["price"] > 100 & df["units"] > 1])Error
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
isin with a text instead of a list:
import pandas as pd
df = pd.read_csv("orders.csv")
print(df[df["city"].isin("Baku")])Error
TypeError: only list-like objects are allowed to be passed to isin(), you passed a `str`
fillna without storing the result:
import pandas as pd
df = pd.read_csv("orders.csv")
df["city"].fillna("Unknown")
print(df["city"].isna().sum())
df["city"] = df["city"].fillna("Unknown")
print(df["city"].isna().sum())Output
8 0
A wrong key name in merge:
import pandas as pd
df = pd.read_csv("orders.csv")
customers = pd.read_csv("customers.csv")
full = df.merge(customers, on="name")Error
KeyError: 'name'
10Solved problems (easy to medium-hard)
Every example was run, and the outputs are real.
10.1Level 1: Easy
Problem 1: The orders of one city
import pandas as pd
df = pd.read_csv("orders.csv")
quba = df[df["city"] == "Quba"]
print(len(quba))
print(quba[["date", "customer", "product"]].head(3))Output
30
date customer product
9 2025-01-19 Konul Mug
17 2025-01-29 Tofiq Mug
21 2025-02-05 Konul Desk lampChange it and run: do the same for Lankaran.
Problem 2: How many gaps?
import pandas as pd
df = pd.read_csv("orders.csv")
gaps = df.isna().sum()
print(gaps[gaps > 0])Output
city 8 rating 36 dtype: int64
Why: isna().sum() is a Series, and a condition keeps only the columns that have gaps.
Problem 3: Orders with five units
import pandas as pd
df = pd.read_csv("orders.csv")
print(df.loc[df["units"] == 5, ["customer", "product", "price"]])Output
customer product price 31 Leyla Cookbook 19.92 44 Javid Novel 12.50 55 Zahra Novel 12.50 58 Anar Yoga mat 27.90 93 Lala Football 28.00 264 Javid Cookbook 24.90
Change it and run: show the orders with 4 units.
Problem 4: Fill the missing cities
import pandas as pd
df = pd.read_csv("orders.csv")
df["city"] = df["city"].fillna("Unknown")
print(df["city"].value_counts().tail(3))Output
city Lankaran 22 Shaki 10 Unknown 8 Name: count, dtype: int64
Change it and run: fill with "?" and print all counts.
Problem 5: The average rating of every category
import pandas as pd
df = pd.read_csv("orders.csv")
print(df.groupby("category")["rating"].mean().round(2))Output
category Books 4.15 Clothing 4.17 Home 3.96 Sports 4.05 Tech 3.98 Name: rating, dtype: float64
Change it and run: print the median rating instead of the mean.
10.2Level 2: Medium
Problem 6: Expensive orders outside Baku
import pandas as pd
df = pd.read_csv("orders.csv")
chosen = df[(df["price"] > 100) & (df["city"] != "Baku")]
print(len(chosen))
print(chosen[["customer", "city", "product", "price"]].head(4))Output
12 customer city product price 1 Ziya Lankaran Jacket 129.0 52 Ayan Shaki Smartwatch 199.2 68 Aida Sumqayit Smartwatch 249.0 76 Ramin Sumqayit Smartwatch 249.0
Change it and run: change the limit to 200.
Why: two conditions with &, each in parentheses. != means "not equal". (The rows without a city are counted too: a missing city is not equal to "Baku".)
Problem 7: Bad ratings
import pandas as pd
df = pd.read_csv("orders.csv")
bad = df[df["rating"] <= 2]
print(len(bad))
print(bad["product"].value_counts().head(2))Output
30 product Power bank 5 Pillow 4 Name: count, dtype: int64
Change it and run: count the ratings of exactly 5 instead.
Why: filter first, then count: these products get the low ratings most often.
Problem 8: A cleaned price column
import pandas as pd
shop = pd.DataFrame({
"product": ["Mug", "Novel", "Jacket", "Pillow"],
"price": ["8.50", "12,50", "129", "unknown"],
})
shop["price"] = shop["price"].str.replace(",", ".")
shop["price"] = pd.to_numeric(shop["price"], errors="coerce")
print(shop)
print(shop["price"].mean())Output
product price 0 Mug 8.5 1 Novel 12.5 2 Jacket 129.0 3 Pillow NaN 50.0
Change it and run: add a fifth product with the price "45,90".
Why: the comma is replaced by a point first. Then to_numeric converts what it can, and "unknown" becomes a missing value, which the mean skips.
Problem 9: The money of every city
import pandas as pd
df = pd.read_csv("orders.csv")
df["city"] = df["city"].fillna("Unknown")
df["total"] = df["price"] * df["units"]
money = df.groupby("city")["total"].sum().sort_values(ascending=False)
print(money.round(2))Output
city Baku 9093.10 Ganja 4213.20 Sumqayit 4201.60 Quba 1986.82 Lankaran 1358.15 Shaki 649.64 Unknown 432.71 Name: total, dtype: float64
Change it and run: leave out the first line. The city Unknown disappears.
Problem 10: The best customers
import pandas as pd
df = pd.read_csv("orders.csv")
df["total"] = df["price"] * df["units"]
best = df.groupby("customer")["total"].agg(["count", "sum"])
print(best.sort_values("sum", ascending=False).head(5).round(2))Output
count sum customer Ramin 28 2538.11 Murad 24 1568.87 Konul 17 1348.08 Aysel 10 1214.83 Aylin 18 1194.38
Change it and run: sort by count instead of sum.
Why: agg gives the number of orders and the money of every customer. Sorting by sum puts the most valuable customers first.
10.3Level 3: Medium-Hard
Problem 11: Orders and money by weekday
import pandas as pd
df = pd.read_csv("orders.csv")
df["total"] = df["price"] * df["units"]
df["weekday"] = pd.to_datetime(df["date"]).dt.day_name()
days = df.groupby("weekday")["total"].agg(["count", "mean"])
print(days.round(2))Output
count mean weekday Friday 45 82.71 Monday 40 63.48 Saturday 39 84.84 Sunday 48 82.35 Thursday 31 75.02 Tuesday 49 63.48 Wednesday 48 62.00
Problem 12: A cleaned table of visitors
import pandas as pd
raw = pd.DataFrame({
"name": [" aylin", "MURAD ", "Leyla", "leyla", "Kamran"],
"city": ["baku", "Baku ", "GANJA", "Ganja", "baku"],
"age": ["20", "25", "twenty-two", "22", "30"],
})
raw["name"] = raw["name"].str.strip().str.title()
raw["city"] = raw["city"].str.strip().str.title()
raw["age"] = pd.to_numeric(raw["age"], errors="coerce")
clean = raw.dropna().drop_duplicates(subset=["name"])
print(clean)
print(clean.groupby("city")["age"].mean())Output
name city age 0 Aylin Baku 20.0 1 Murad Baku 25.0 3 Leyla Ganja 22.0 4 Kamran Baku 30.0 city Baku 25.0 Ganja 22.0 Name: age, dtype: float64
Change it and run: change "twenty-two" to "22". The row stays, and the second Leyla is removed as a duplicate.
Why: text first, then the numbers, then the row with a gap is removed, then the duplicates. After the cleaning, a groupby gives correct groups.
Problem 13: Age groups
import pandas as pd
df = pd.read_csv("orders.csv")
customers = pd.read_csv("customers.csv")
full = df.merge(customers, on="customer", how="left")
full["total"] = full["price"] * full["units"]
full["group"] = "30 and older"
full.loc[full["age"] < 30, "group"] = "under 30"
full.loc[full["age"].isna(), "group"] = "unknown"
print(full.groupby("group")["total"].agg(["count", "mean"]).round(2))Output
count mean group 30 and older 212 75.51 under 30 85 67.26 unknown 3 70.22
Change it and run: use 40 as the limit instead of 30.
Why: a new column starts with one value, and loc with a condition changes it for the chosen rows. The customers without an age get their own group, so no order is lost.
Problem 14: Customers who never ordered
import pandas as pd
df = pd.read_csv("orders.csv")
customers = pd.read_csv("customers.csv")
buyers = df["customer"].unique()
quiet = customers[~customers["customer"].isin(buyers)]
print(quiet)Output
customer age gender joined 38 Elchin 24 M 2025 39 Maryam 36 F 2023
Why: isin marks the customers who appear in the orders, and ~ turns the mask around.
Problem 15: The best month of every category
import pandas as pd
df = pd.read_csv("orders.csv")
df["total"] = df["price"] * df["units"]
df["month"] = pd.to_datetime(df["date"]).dt.month
table = df.pivot_table(index="category", columns="month", values="total", aggfunc="sum")
print(table.idxmax(axis=1))
print(table.max(axis=1).round(2))Output
category Books 9 Clothing 10 Home 11 Sports 5 Tech 6 dtype: int32 category Books 557.32 Clothing 992.29 Home 763.39 Sports 539.51 Tech 1542.14 dtype: float64
Change it and run: group by city instead of category: the best month of every city.
Why: the pivot table has one row for every category and one column for every month. idxmax(axis=1) finds the month with the most money in each row, and max(axis=1) the money itself.
11Practice problems (try them yourself)
Fifteen problems in three levels. They work like one notebook: the setup cell below reads both files, and every problem is a cell that continues from it. So df and customers are already there.
import pandas as pd
df = pd.read_csv("orders.csv")
customers = pd.read_csv("customers.csv")Press Run to try your code, then Check. A problem that says it continues from another problem uses your own answer to that problem: it is run first, so the earlier answer must be right for the later one to be right. This is how a real notebook works.
Easy
One condition, two conditions and a first group.
- 1.Print how many orders the city Ganja has.
Show a hint
The conditiondf["city"] == "Ganja"chooses the rows.len(...)counts them.Show one possible solution
Python, continues from the cells aboveprint(len(df[df["city"] == "Ganja"]))Output
54
- 2.Print the rows where the rating is missing and the price is above 80.
Show a hint
Two masks joined with&:df["rating"].isna()and(df["price"] > 80). The comparison needs parentheses.Show one possible solution
Python, continues from the cells aboveprint(df[df["rating"].isna() & (df["price"] > 80)])Output
date customer city category product price units rating 76 2025-05-02 Ramin Sumqayit Tech Smartwatch 249.00 1 NaN 80 2025-05-09 Konul Quba Clothing Jacket 129.00 1 NaN 117 2025-06-17 Ruslan Shaki Tech Headphones 80.91 1 NaN 221 2025-10-22 Aylin Baku Clothing Sneakers 89.91 1 NaN 261 2025-12-02 Ramin Sumqayit Tech Headphones 89.90 1 NaN 278 2025-12-20 Orkhan Baku Clothing Sneakers 99.90 2 NaN
- 3.Print the average price of every city, rounded to 2 decimals.
Show a hint
Group bycity, take the columnprice, calculate the mean:df.groupby("city")["price"].mean(). Then.round(2).Show one possible solution
Python, continues from the cells aboveprint(df.groupby("city")["price"].mean().round(2))Output
city Baku 48.84 Ganja 54.11 Lankaran 34.94 Quba 49.91 Shaki 56.50 Sumqayit 58.64 Name: price, dtype: float64
- 4.Print the number of orders of every category whose product was bought with exactly 1 unit. Use
groupbyandsize.Show a hint
First keep the rows withdf["units"] == 1, then group the result bycategoryand call.size().Show one possible solution
Python, continues from the cells abovesingle = df[df["units"] == 1] print(single.groupby("category").size())Output
category Books 36 Clothing 36 Home 22 Sports 23 Tech 52 dtype: int64
Medium
Filling gaps, isin and between, a new column and several summaries.
- 5.Read the name of a city. Print how many orders this city has and their average price, rounded to 2 decimals, on one line.Examples:
Bakugives128 48.84Ganjagives54 54.11Shakigives10 56.5Show a hint
Keep the rows of the city in a variable. Thenprint(len(rows), round(rows["price"].mean(), 2)).Show one possible solution
Python, continues from the cells abovecity = input() rows = df[df["city"] == city] print(len(rows), round(rows["price"].mean(), 2))Output
128 48.84
- 6.Fill the missing ratings with the mean rating, rounded to 1 decimal. Print how many ratings are missing after it, and the new mean rounded to 2 decimals.
Show a hint
Store the rounded mean first.df["rating"] = df["rating"].fillna(mean)fills the gaps: remember to store the result. Thenisna().sum()and the mean again.Show one possible solution
Python, continues from the cells abovemean = round(df["rating"].mean(), 1) df["rating"] = df["rating"].fillna(mean) print(df["rating"].isna().sum()) print(round(df["rating"].mean(), 2))Output
0 4.07
- 7.Print the orders of the categories Books and Home with a price between 20 and 30, with the columns
productandprice: only the first 5 rows.Show a hint
df["category"].isin(["Books", "Home"])anddf["price"].between(20, 30), joined with&. Then choose the two columns and take.head(5).Show one possible solution
Python, continues from the cells abovechosen = df[df["category"].isin(["Books", "Home"]) & df["price"].between(20, 30)] print(chosen[["product", "price"]].head(5))Output
product price 2 Cookbook 24.90 3 Cookbook 24.90 4 Dictionary 29.90 16 Dictionary 29.90 25 Cookbook 22.41
- 8.Add a column
total(price times units). Print the money of every category, the largest first, rounded to 2 decimals.Show a hint
df["total"] = df["price"] * df["units"]. Then group bycategory, sum the columntotal, sort withsort_values(ascending=False)and round.Show one possible solution
Python, continues from the cells abovedf["total"] = df["price"] * df["units"] money = df.groupby("category")["total"].sum() print(money.sort_values(ascending=False).round(2))Output
category Tech 7424.00 Clothing 4846.81 Books 3629.74 Sports 3297.39 Home 2737.28 Name: total, dtype: float64
- 9.Print, for every category, the number of orders, the mean price and the highest price, in this order, rounded to 2 decimals.
Show a hint
Onegroupbywith a list of summaries:.agg(["count", "mean", "max"])on the columnprice.Show one possible solution
Python, continues from the cells aboveprint(df.groupby("category")["price"].agg(["count", "mean", "max"]).round(2))Output
count mean max category Books 74 25.44 39.9 Clothing 54 70.59 129.0 Home 56 26.79 49.9 Sports 48 38.99 54.9 Tech 68 90.08 249.0
Medium-Hard
Dates, joining two tables, a pivot table, a function, and problems that build on each other.
- 10.Add a column
month. Print the three months with the most orders. Usevalue_counts.Show a hint
pd.to_datetime(df["date"]).dt.monthgives the month of every order.value_counts()puts the most frequent first, and.head(3)takes three.Show one possible solution
Python, continues from the cells abovedf["month"] = pd.to_datetime(df["date"]).dt.month print(df["month"].value_counts().head(3))Output
month 12 40 11 34 9 28 Name: count, dtype: int64
- 11.Join the orders with
customersand keep all orders: store the result infull. Print how many orders have no age, and the average age of the customers of each city, rounded to 1 decimal.Show a hint
full = df.merge(customers, on="customer", how="left"). The gaps:full["age"].isna().sum(). Then groupfullbycityand take the mean ofage.Show one possible solution
Python, continues from the cells abovefull = df.merge(customers, on="customer", how="left") print(full["age"].isna().sum()) print(full.groupby("city")["age"].mean().round(1))Output
3 city Baku 45.6 Ganja 37.2 Lankaran 28.0 Quba 30.5 Shaki 47.3 Sumqayit 38.7 Name: age, dtype: float64
- 12.This problem continues from Problem 8: the table already has the column
totalfrom your answer there. Read a category. Print the name of the customer who spent the most money in this category.Examples:BooksgivesZiyaTechgivesRaminHomegivesRaminShow a hint
Keep the rows of the category, group them bycustomer, sum the columntotal..idxmax()gives the name with the largest sum. If Python says there is no columntotal, finish Problem 8 first.Show one possible solution
Python, continues from the cells abovecategory = input() rows = df[df["category"] == category] spent = rows.groupby("customer")["total"].sum() print(spent.idxmax())Output
Ziya
- 13.Print a table with the cities in the rows, the categories in the columns and the number of orders in the cells. Use
pivot_tableand count the columnprice.Show a hint
df.pivot_table(index="city", columns="category", values="price", aggfunc="count").Show one possible solution
Python, continues from the cells abovetable = df.pivot_table(index="city", columns="category", values="price", aggfunc="count") print(table)Output
category Books Clothing Home Sports Tech city Baku 29.0 28.0 21.0 25.0 25.0 Ganja 17.0 10.0 7.0 10.0 10.0 Lankaran 9.0 2.0 7.0 3.0 1.0 Quba 5.0 4.0 9.0 2.0 10.0 Shaki 3.0 2.0 NaN 2.0 3.0 Sumqayit 11.0 5.0 9.0 5.0 18.0
- 14.Write a function
clean_names(column)that removes the spaces at both ends and writes every name with a capital first letter, and returns the cleaned column.Show a hint
The whole function is one line:return column.str.strip().str.title().Show one possible solution
Python, continues from the cells abovedef clean_names(column): return column.str.strip().str.title() names = pd.Series([" aylin", "MURAD ", "leyla ", "Kamran"]) print(clean_names(names).tolist())Output
['Aylin', 'Murad', 'Leyla', 'Kamran']
- 15.This problem continues from Problem 8: the table already has the column
total. Join the orders with the customers (the default join is right here: an order without a customer has no year). Print the money of the customers who joined in each year, the largest first, rounded to 2 decimals.Show a hint
joined = df.merge(customers, on="customer"). Then group byjoined, sumtotal, sort withascending=Falseand round.Show one possible solution
Python, continues from the cells abovejoined = df.merge(customers, on="customer") money = joined.groupby("joined")["total"].sum() print(money.sort_values(ascending=False).round(2))Output
joined 2024 6362.77 2025 5263.75 2023 5154.50 2021 3596.13 2022 1347.42 Name: total, dtype: float64
12Check yourself
Twelve quick questions. Your answers are saved in this browser, so you can leave the page and continue later. Each finished round is kept as an attempt below the questions; you can delete the attempts at any time.
0 of 12 answered.
13Quick summary
| Concept | What it does | Example |
|---|---|---|
| Mask | True/False for every row | df["price"] > 100 |
| Filter | the rows where the mask is True | df[df["price"] > 100] |
&, |, ~ | and, or, not | (a) & (b) |
isin / between | one of a list / from a to b | df["city"].isin(["Shaki", "Quba"]) |
str.contains | the text has this piece | df["product"].str.contains("book") |
isna / notna | missing / not missing | df.isna().sum() |
dropna / fillna | removes / fills gaps | df["city"].fillna("Unknown") |
duplicated / drop_duplicates | finds / removes repeated rows | df.drop_duplicates() |
pd.to_numeric | text to numbers | pd.to_numeric(col, errors="coerce") |
pd.to_datetime / .dt | text to dates / parts of a date | df["date"].dt.month |
select_dtypes | columns of one kind | df.select_dtypes(include="number") |
.str methods | cleans text | col.str.strip().str.title() |
groupby | a summary for every group | df.groupby("city")["price"].mean() |
agg | several summaries | .agg(["count", "mean"]) |
pivot_table | groups in rows and columns | df.pivot_table(index=, columns=, values=) |
merge | joins two tables by a key | df.merge(customers, on="customer", how="left") |
concat | stacks tables | pd.concat([a, b], ignore_index=True) |