Module 1, topic 10, week 5, Thursday
Pandas fundamentals: Series and DataFrames, reading data
Series and DataFrames, reading a CSV file, a first look at a table, choosing columns and rows with iloc and loc, sorting, and new columns
Lesson notebook
The lesson as a Jupyter notebook: the explanations, every example and the 15 solved problems, ready to run and change.
topic-10-pandas-series-dataframes.ipynb, 67 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-10-practice.ipynb, 23 KB
Data file
300 orders of an invented online shop in 2025. Every example with real data reads this file, and the next lessons use it too.
orders.csv, 14 KB
Introduction: pandas, Series and DataFrames
A beginner-friendly guide to pandas, the library for working with tables of data in Python. It starts with the two building blocks, the Series (one column) and the DataFrame (a whole table). Then it reads a real data file and shows how to look at a table, how to choose columns and rows with [], iloc and loc, how to sort a table and how to add new columns. 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 lists, dictionaries and NumPy arrays: indexes, slices and calculations on whole arrays.
The data file. All examples with real data use one file, orders.csv: 300 orders of a small online shop in 2025. Put the file into the same folder as your notebook. The next lessons use the same file.
On this page the file is already there for every example. You can look at the whole table before you start.
This lesson and the next one. This lesson is about reading a table, looking at it and choosing parts of it. The next lesson continues with missing values, choosing rows by a condition, joining two tables and grouping. Those topics are left out here on purpose.
What you will learn
- 1.What pandas is, and what a Series and a DataFrame are
- 2.Creating a Series, and reaching its values by label and by position
- 3.Creating a DataFrame from a dictionary
- 4.Reading a CSV file with
read_csv, and saving one withto_csv - 5.A first look at a table:
head,tail,shape,dtypes,info,describe - 6.Choosing columns, and summaries of a column:
mean,unique,value_counts - 7.Choosing rows with
iloc(by position) andloc(by label) - 8.Sorting with
sort_values - 9.New columns, renaming and removing columns
- 10.15 solved problems and practice problems
1pandas and the Series
1.1What is pandas?
pandas is a package for working with tables of data: rows and columns with names, like a spreadsheet. It is built on NumPy, and almost every data project in Python starts with it: reading a file, looking at the data, preparing it for charts and models.
With Anaconda, pandas is already installed. Everybody imports it with the short name pd:
import pandas as pd
print(pd.__version__)Output
3.0.2
1.2Two building blocks
| What it is | Think of it as | |
|---|---|---|
| Series | one column of values, and every value has a label | one column of a spreadsheet |
| DataFrame | a table: several columns side by side | the whole spreadsheet |
A DataFrame is made of Series: every column of a DataFrame is a Series.
1.3Why not just a NumPy array?
| NumPy array | pandas DataFrame | |
|---|---|---|
| Types | one type for all items | every column has its own type |
| Rows and columns | reached by position | have names (labels) |
| Made for | numbers and calculation | real data: names, dates, prices, gaps |
| Reading files | not its job | one line for a CSV or an Excel file |
What you learned about arrays still works: calculations on whole columns, sum, mean, max.
1.4A Series from a list
grades = pd.Series([85, 92, 78, 60])
print(grades)Output
0 85 1 92 2 78 3 60 dtype: int64
Change it and run: add a fifth grade to the list. Which label does it get?
The left side is the index: the labels of the values. If you give no labels, pandas numbers them from 0. The right side holds the values, and the last line shows their type.
1.5Your own labels
grades = pd.Series([85, 92, 78, 60], index=["Aylin", "Murad", "Leyla", "Kamran"])
print(grades)Output
Aylin 85 Murad 92 Leyla 78 Kamran 60 dtype: int64
Change it and run: change the label Kamran to your own name.
Now every value has a name. This is the big difference from a NumPy array.
index: the labels
values
dtype: int64
1.6A Series from a dictionary
The keys become the labels:
prices = pd.Series({"apple": 1.5, "bread": 0.8, "milk": 2.0})
print(prices)Output
apple 1.5 bread 0.8 milk 2.0 dtype: float64
Change it and run: add "eggs": 3.2 to the dictionary.
1.7The parts of a Series
print(grades.values)
print(grades.index)
print(grades.dtype)
print(grades.size)Output
[85 92 78 60] Index(['Aylin', 'Murad', 'Leyla', 'Kamran'], dtype='str') int64 4
values is a NumPy array. index holds the labels. dtype and size mean the same as for an array.
1.8Reaching a value: by label or by position
print(grades["Murad"])
print(grades.loc["Murad"])
print(grades.iloc[1])
print(grades.iloc[-1])Output
92 92 92 60
Change it and run: print Leyla's grade in two ways: with her label and with her position.
loc uses the label. iloc uses the position, counted from 0 as in a list (the i stands for integer). Square brackets alone work with labels.
1.9Several values, and slices
print(grades[["Aylin", "Leyla"]])
print(grades.iloc[1:3])
print(grades.loc["Murad":"Kamran"])Output
Aylin 85 Leyla 78 dtype: int64 Murad 92 Leyla 78 dtype: int64 Murad 92 Leyla 78 Kamran 60 dtype: int64
Change it and run: print the first three grades with iloc, then the same three with loc.
A slice by position stops before its end, as always. A slice by label includes its end: "Murad":"Kamran" takes Kamran too.
1.10A label that does not exist
print(grades["Nigar"])Error
KeyError: 'Nigar'
in checks whether a label exists: "Nigar" in grades gives False.
1.11Changing and adding values
grades["Murad"] = 95
grades["Nigar"] = 70
print(grades)Output
Aylin 85 Murad 95 Leyla 78 Kamran 60 Nigar 70 dtype: int64
Change it and run: give Aylin the grade 100.
A label that exists is changed. A new label is added at the end, as in a dictionary.
1.12Calculations on a whole Series
A Series calculates like a NumPy array: on every value at once. The labels stay.
grades = pd.Series([85, 92, 78, 60], index=["Aylin", "Murad", "Leyla", "Kamran"])
print(grades + 5)
print(grades / 100)Output
Aylin 90 Murad 97 Leyla 83 Kamran 65 dtype: int64 Aylin 0.85 Murad 0.92 Leyla 0.78 Kamran 0.60 dtype: float64
Change it and run: print grades * 2.
1.13Summaries
print(grades.sum())
print(grades.mean())
print(grades.min(), grades.max())
print(grades.idxmax())
print(grades.idxmin())Output
315 78.75 60 92 Murad Kamran
Change it and run: change Kamran's grade from 60 to 99 in the list. Which results change?
idxmax and idxmin give the label of the largest and the smallest value. (NumPy's argmax gave the position.)
1.14Sorting a Series
print(grades.sort_values())
print(grades.sort_values(ascending=False))
print(grades.sort_index())Output
Kamran 60 Leyla 78 Aylin 85 Murad 92 dtype: int64 Murad 92 Aylin 85 Leyla 78 Kamran 60 dtype: int64 Aylin 85 Kamran 60 Leyla 78 Murad 92 dtype: int64
Change it and run: print only the two best grades: grades.sort_values(ascending=False).iloc[:2].
sort_values sorts by the values, sort_index sorts by the labels. Each value keeps its label. All three give a new Series: grades itself is not changed.
1.15From a Series to a list or an array
print(grades.tolist())
print(grades.to_numpy())Output
[85, 92, 78, 60] [85 92 78 60]
| You write | You get |
|---|---|
pd.Series([85, 92], index=["Aylin", "Murad"]) | a Series with your own labels |
s["Murad"], s.loc["Murad"] | the value with this label |
s.iloc[0], s.iloc[-1] | the value at this position |
s[["Aylin", "Leyla"]] | several values, as a Series |
s.iloc[1:3] | a slice by position: the end is not included |
s.loc["Murad":"Kamran"] | a slice by label: the end is included |
s.sum(), s.mean(), s.min(), s.max() | summaries |
s.idxmax(), s.idxmin() | the label of the largest / smallest value |
s.sort_values(), s.sort_index() | a sorted copy |
s.tolist(), s.to_numpy() | a list / a NumPy array |
Try it yourself
prices with the labels apple, bread and milk and the prices 1.5, 0.9 and 2.1. Print the price of bread, then the mean price.Show a hint
pd.Series([...], index=[...]). One value is reached with its label: prices["bread"]. The mean is prices.mean().Show the solution
import pandas as pd
prices = pd.Series([1.5, 0.9, 2.1], index=["apple", "bread", "milk"])
print(prices["bread"])
print(prices.mean())Output
0.9 1.5
2DataFrames
2.1A DataFrame from a dictionary
Each key is the name of a column, and each list holds the values of that column:
import pandas as pd
df = pd.DataFrame({
"name": ["Aylin", "Murad", "Leyla", "Kamran"],
"age": [20, 25, 22, 30],
"grade": [85.5, 92.0, 78.0, 60.5],
})
print(df)Output
name age grade 0 Aylin 20 85.5 1 Murad 25 92.0 2 Leyla 22 78.0 3 Kamran 30 60.5
Change it and run: add a fourth column, "city", with four cities.
The name df is short for DataFrame. Almost everybody uses it.
| name | age | grade | |
|---|---|---|---|
| 0 | Aylin | 20 | 85.5 |
| 1 | Murad | 25 | 92.0 |
| 2 | Leyla | 22 | 78.0 |
| 3 | Kamran | 30 | 60.5 |
- Columns: the names on top.
- Index: the row labels on the left, here 0 to 3.
- Values: everything inside.
df["age"].A DataFrame has three parts: the columns (their names are on top), the index (the row labels on the left) and the values.
2.2The lists must have the same length
df = pd.DataFrame({
"name": ["Aylin", "Murad", "Leyla"],
"age": [20, 25],
})Error
ValueError: All arrays must be of the same length
2.3The properties of a DataFrame
print(df.shape)
print(len(df))
print(df.columns)
print(df.index)
print(df.dtypes)Output
(4, 3) 4 Index(['name', 'age', 'grade'], dtype='str') RangeIndex(start=0, stop=4, step=1) name str age int64 grade float64 dtype: object
Change it and run: add a fifth student to the three lists. What is the shape now?
shape is (rows, columns), as in NumPy, and len is the number of rows. dtypes lists the type of every column. (Its last line, dtype: object, belongs to that list itself, not to the table.)
| dtype | Meaning |
|---|---|
int64 | whole numbers |
float64 | decimals |
str | text (older pandas versions show object here) |
bool | True and False |
datetime64 | dates (Part 3) |
2.4Every column is a Series
ages = df["age"]
print(ages)
print(type(ages))
print(ages.mean())Output
0 20 1 25 2 22 3 30 Name: age, dtype: int64 <class 'pandas.Series'> 24.25
Change it and run: print the grade column and its largest value.
The column has the same index as the table, and its name is the column name. Everything about a Series from Part 1 works on it.
2.5A DataFrame from a list of rows
When the data comes row by row, use a list of dictionaries. Each dictionary is one row:
rows = [
{"name": "Aylin", "age": 20},
{"name": "Murad", "age": 25},
{"name": "Leyla", "age": 22},
]
df = pd.DataFrame(rows)
print(df)Output
name age 0 Aylin 20 1 Murad 25 2 Leyla 22
Change it and run: add a fourth row, {"name": "Kamran", "age": 30}.
2.6Your own row labels
As with a Series, index= gives the rows your own labels:
students = pd.DataFrame(
{"age": [20, 25, 22, 30], "grade": [85.5, 92.0, 78.0, 60.5]},
index=["Aylin", "Murad", "Leyla", "Kamran"],
)
print(students)Output
age grade Aylin 20 85.5 Murad 25 92.0 Leyla 22 78.0 Kamran 30 60.5
Now the names are not a column. They are the labels of the rows. We use this table again in Part 7.
Try it yourself
name and age. Print its shape and the mean age.Show a hint
pd.DataFrame({"name": names, "age": ages}). The mean age is the mean of the column age.Show the solution
import pandas as pd
names = ["Aylin", "Murad", "Leyla", "Kamran"]
ages = [20, 25, 22, 31]
people = pd.DataFrame({"name": names, "age": ages})
print(people.shape)
print(people["age"].mean())Output
(4, 2) 24.5
3Reading data
Real data is not typed by hand. It comes from files.
3.1What is a CSV file?
CSV means "comma-separated values". It is a plain text file: one line for every row, the values separated by commas, and the column names in the first line. These are the first lines of orders.csv:
date,customer,city,category,product,price,units,rating 2025-01-01,Nigar,Baku,Home,Mug,8.50,2,5 2025-01-03,Ziya,Lankaran,Clothing,Jacket,129.00,1,3 2025-01-11,Anar,Ganja,Books,Cookbook,24.90,4,5
3.2read_csv
One line reads the whole file into a DataFrame:
import pandas as pd
df = pd.read_csv("orders.csv")
print(df)Output
date customer city category product price units rating 0 2025-01-01 Nigar Baku Home Mug 8.50 2 5.0 1 2025-01-03 Ziya Lankaran Clothing Jacket 129.00 1 3.0 2 2025-01-11 Anar Ganja Books Cookbook 24.90 4 5.0 3 2025-01-13 Gunel Baku Books Cookbook 24.90 2 4.0 4 2025-01-14 Leyla Baku Books Dictionary 29.90 1 3.0 .. ... ... ... ... ... ... ... ... 295 2025-12-29 Aylin Baku Home Desk lamp 31.41 2 5.0 296 2025-12-30 Leyla Baku Home Desk lamp 31.41 2 4.0 297 2025-12-30 Konul Quba Books Cookbook 24.90 3 5.0 298 2025-12-31 Nigar Baku Sports Football 35.00 2 3.0 299 2025-12-31 Ziya Lankaran Books Textbook 39.90 2 2.0 [300 rows x 8 columns]
Change it and run: print len(df): the number of rows.
A long table is printed in a short form: the first five and the last five rows, and its size below.
The file must be in the same folder as your notebook. If it is somewhere else, write the path: pd.read_csv("data/orders.csv").
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 ...
3.3The columns of orders.csv
| Column | Meaning | Example |
|---|---|---|
date | the day of the order | 2025-01-03 |
customer | the first name of the customer | Ziya |
city | the city of the customer | Lankaran |
category | the product group: Tech, Clothing, Books, Home or Sports | Clothing |
product | what was bought | Jacket |
price | the price of one unit, in AZN | 129.00 |
units | how many units were bought | 1 |
rating | the customer's rating from 1 to 5 (some customers gave none) | 3 |
3.4Useful options of read_csv
| Option | What it does | Example |
|---|---|---|
usecols | reads only some columns | usecols=["date", "price"] |
nrows | reads only the first rows | nrows=100 |
sep | the separator, if it is not a comma | sep=";" |
index_col | uses a column as the row labels | index_col="date" |
parse_dates | reads a column as real dates | parse_dates=["date"] |
small = pd.read_csv("orders.csv", usecols=["product", "price", "units"], nrows=4)
print(small)Output
product price units 0 Mug 8.5 2 1 Jacket 129.0 1 2 Cookbook 24.9 4 3 Cookbook 24.9 2
Change it and run: read the columns date and city and the first 6 rows.
3.5Dates
read_csv reads the date column as text. With parse_dates the column holds real dates. They can be compared and sorted, and later used for charts over time:
df = pd.read_csv("orders.csv", parse_dates=["date"])
print(df["date"].dtype)
print(df["date"].min())
print(df["date"].max())Output
datetime64[us] 2025-01-01 00:00:00 2025-12-31 00:00:00
Change it and run: remove the parse_dates option and run it again. The type is str: the dates are only text.
The first and the last order of the year. (The letters in the brackets of datetime64[...] can differ between pandas versions.)
3.6Excel files
An Excel file is read in the same way, with read_excel:
import pandas as pd
df = pd.read_excel("orders.xlsx")3.7Saving a table: to_csv
df = pd.read_csv("orders.csv")
first = df.head(3)
first.to_csv("first_orders.csv", index=False)
with open("first_orders.csv") as file:
print(file.read())Output
date,customer,city,category,product,price,units,rating 2025-01-01,Nigar,Baku,Home,Mug,8.5,2,5.0 2025-01-03,Ziya,Lankaran,Clothing,Jacket,129.0,1,3.0 2025-01-11,Anar,Ganja,Books,Cookbook,24.9,4,5.0
Change it and run: save the first 5 rows instead.
to_csv writes a table into a new file. index=False leaves out the row labels 0, 1, 2. Without it the file gets an extra first column.
Try it yourself
customer, city and price of orders.csv, and only the first 5 rows. Print the table.Show a hint
read_csv: usecols=[...] for the columns and nrows=5 for the rows.Show the solution
import pandas as pd
small = pd.read_csv("orders.csv", usecols=["customer", "city", "price"], nrows=5)
print(small)Output
customer city price 0 Nigar Baku 8.5 1 Ziya Lankaran 129.0 2 Anar Ganja 24.9 3 Gunel Baku 24.9 4 Leyla Baku 29.9
4A first look at a table
Before you work with a table, look at it. These are the first lines of almost every data project.
4.1head and tail
import pandas as pd
df = pd.read_csv("orders.csv")
print(df.head())
print(df.tail(3))Output
date customer city category product price units rating
0 2025-01-01 Nigar Baku Home Mug 8.5 2 5.0
1 2025-01-03 Ziya Lankaran Clothing Jacket 129.0 1 3.0
2 2025-01-11 Anar Ganja Books Cookbook 24.9 4 5.0
3 2025-01-13 Gunel Baku Books Cookbook 24.9 2 4.0
4 2025-01-14 Leyla Baku Books Dictionary 29.9 1 3.0
date customer city category product price units rating
297 2025-12-30 Konul Quba Books Cookbook 24.9 3 5.0
298 2025-12-31 Nigar Baku Sports Football 35.0 2 3.0
299 2025-12-31 Ziya Lankaran Books Textbook 39.9 2 2.0Change it and run: print the first 2 rows and the last 6.
head() gives the first 5 rows, tail() the last 5. A number in the parentheses changes how many.
4.2shape, the column names and the types
print(df.shape)
print(df.columns.tolist())
print(df.dtypes)Output
(300, 8) ['date', 'customer', 'city', 'category', 'product', 'price', 'units', 'rating'] date str customer str city str category str product str price float64 units int64 rating float64 dtype: object
300 rows and 8 columns. columns.tolist() gives the names as a normal list. Five columns are text, price and rating are decimals and units is a whole number.
4.3info: everything in one summary
df.info()Output
<class 'pandas.DataFrame'> RangeIndex: 300 entries, 0 to 299 Data columns (total 8 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 date 300 non-null str 1 customer 300 non-null str 2 city 292 non-null str 3 category 300 non-null str 4 product 300 non-null str 5 price 300 non-null float64 6 units 300 non-null int64 7 rating 264 non-null float64 dtypes: float64(2), int64(1), str(5) memory usage: 18.9 KB
For every column you see its name, how many values are not missing, and its type. city has only 292 values and rating only 264: the others are missing. info prints by itself, so it needs no print. The last line is the memory the table uses, and this number can be different on your computer.
4.4Missing values look like NaN
print(df.head(10))Output
date customer city category product price units rating 0 2025-01-01 Nigar Baku Home Mug 8.50 2 5.0 1 2025-01-03 Ziya Lankaran Clothing Jacket 129.00 1 3.0 2 2025-01-11 Anar Ganja Books Cookbook 24.90 4 5.0 3 2025-01-13 Gunel Baku Books Cookbook 24.90 2 4.0 4 2025-01-14 Leyla Baku Books Dictionary 29.90 1 3.0 5 2025-01-15 Elvin Baku Clothing Jeans 64.90 1 4.0 6 2025-01-15 Aida Sumqayit Tech Keyboard 53.91 1 4.0 7 2025-01-17 Rashad Baku Sports Dumbbells 49.41 1 5.0 8 2025-01-18 Vusal Ganja Home Mug 8.50 2 4.0 9 2025-01-19 Konul Quba Home Mug 8.50 3 NaN
Change it and run: print df.head(16). A second missing rating appears in row 14.
Look at row 9: the customer gave no rating. pandas shows a missing value as NaN ("not a number"). Because of these gaps the rating column is stored as decimals: 5.0, not 5. What to do with missing values is the subject of the next lesson.
4.5describe: statistics of the number columns
print(df.describe())Output
price units rating count 300.000000 300.000000 264.000000 mean 50.638633 1.733333 4.064394 std 45.074383 1.012739 1.130136 min 6.800000 1.000000 1.000000 25% 24.900000 1.000000 4.000000 50% 35.960000 1.000000 4.000000 75% 59.900000 2.000000 5.000000 max 249.000000 5.000000 5.000000
Change it and run: print df.describe().round(1). The numbers are easier to read.
| Row | Meaning |
|---|---|
count | how many values are not missing |
mean | the average |
std | the standard deviation: how spread out the values are (you will meet it in the statistics lessons) |
min, max | the smallest and the largest value |
25%, 50%, 75% | a quarter, a half and three quarters of the values are below this number |
The 50% row is the median. Read the price column: half of the prices are below 35.96, but the mean is 50.64, because a few expensive products pull it up.
| You write | You see |
|---|---|
df.head(), df.tail() | the first / last 5 rows |
df.shape | (rows, columns) |
df.columns.tolist() | the column names as a list |
df.dtypes | the type of every column |
df.info() | names, missing values and types in one summary |
df.describe() | statistics of the number columns |
Try it yourself
Show a hint
df.tail(4) and len(df).Show the solution
import pandas as pd
df = pd.read_csv("orders.csv")
print(df.tail(4))
print(len(df))Output
date customer city category product price units rating 296 2025-12-30 Leyla Baku Home Desk lamp 31.41 2 4.0 297 2025-12-30 Konul Quba Books Cookbook 24.90 3 5.0 298 2025-12-31 Nigar Baku Sports Football 35.00 2 3.0 299 2025-12-31 Ziya Lankaran Books Textbook 39.90 2 2.0 300
5Choosing columns
5.1One column
import pandas as pd
df = pd.read_csv("orders.csv")
products = df["product"]
print(products.head())
print(type(products))Output
0 Mug 1 Jacket 2 Cookbook 3 Cookbook 4 Dictionary Name: product, dtype: str <class 'pandas.Series'>
Change it and run: print the first five customers.
The column name in square brackets gives that column as a Series.
5.2Several columns
print(df[["product", "price", "units"]].head())Output
product price units 0 Mug 8.5 2 1 Jacket 129.0 1 2 Cookbook 24.9 4 3 Cookbook 24.9 2 4 Dictionary 29.9 1
Change it and run: change the order of the three names in the list.
Notice the double brackets: the inner pair is a list of column names. The result is a DataFrame, with the columns in the order you asked for.
5.3One pair of brackets or two?
print(df["price"].shape)
print(df[["price"]].shape)Output
(300,) (300, 1)
df["price"] is a Series: one dimension. df[["price"]] is a DataFrame with one column: two dimensions.
df["price"]
A Series: one dimension, shape (300,)
| 0 | 8.5 |
|---|---|
| 1 | 129.0 |
| 2 | 24.9 |
df[["product", "price"]]
A DataFrame: two dimensions, shape (300, 2)
| product | price | |
|---|---|---|
| 0 | Mug | 8.5 |
| 1 | Jacket | 129.0 |
| 2 | Cookbook | 24.9 |
5.4The short way with a dot
df.price means the same as df["price"]:
print(df.price.head(3))Output
0 8.5 1 129.0 2 24.9 Name: price, dtype: float64
It works only for simple names without spaces, and it cannot create a new column. This guide uses the brackets everywhere.
5.5Summaries of a column
print(round(df["price"].mean(), 2))
print(df["price"].median())
print(df["price"].min(), df["price"].max())
print(df["units"].sum())Output
50.64 35.96 6.8 249.0 520
Change it and run: print the mean and the largest number of units.
The average price, the median price, the cheapest and the most expensive price, and the number of units sold in the whole year.
5.6Missing values are skipped
print(len(df["rating"]))
print(df["rating"].count())
print(round(df["rating"].mean(), 2))Output
300 264 4.06
Change it and run: do the same for the column city: len and count.
The column has 300 places, but count counts only the 264 ratings that exist. The mean is calculated from those 264.
5.7Summaries of several columns
print(df[["price", "units", "rating"]].mean())
print(df[["price", "units"]].max())Output
price 50.638633 units 1.733333 rating 4.064394 dtype: float64 price 249.0 units 5.0 dtype: float64
A summary of a table gives one result for every column, as a Series.
5.8Which values are there? unique and nunique
print(df["category"].unique().tolist())
print(df["category"].nunique())
print(df["customer"].nunique())
print(df["product"].nunique())Output
['Home', 'Clothing', 'Books', 'Tech', 'Sports'] 5 40 20
Change it and run: print the different cities, and how many there are.
unique gives the different values, and tolist() turns them into a normal list. nunique counts them: 5 categories, 40 customers, 20 products.
5.9How often? value_counts
print(df["city"].value_counts())Output
city Baku 128 Ganja 54 Sumqayit 48 Quba 30 Lankaran 22 Shaki 10 Name: count, dtype: int64
Change it and run: count the products instead of the cities.
value_counts counts how often every value appears, the most frequent first. It is one of the most used methods in pandas. The counts add up to 292, because 8 orders have no city.
The result is a Series, and the values of the column are its labels:
counts = df["category"].value_counts()
print(counts["Books"])
print(counts.idxmax())
print(df["customer"].value_counts().head(3))Output
74 Books customer Ramin 28 Murad 24 Aylin 18 Name: count, dtype: int64
Change it and run: print how many orders are in the category "Tech".
5.10Shares instead of counts
print(df["category"].value_counts(normalize=True).round(2))Output
category Books 0.25 Tech 0.23 Home 0.19 Clothing 0.18 Sports 0.16 Name: proportion, dtype: float64
Change it and run: multiply the result by 100 to get percent.
With normalize=True the result is the share of every value: 0.25 means 25% of the orders.
| You write | You get |
|---|---|
df["price"] | one column, as a Series |
df[["product", "price"]] | several columns, as a DataFrame |
df["price"].mean(), .median(), .min(), .max(), .sum() | a summary of the column |
df["rating"].count() | how many values are not missing |
df["category"].unique().tolist() | the different values |
df["category"].nunique() | how many different values |
df["city"].value_counts() | how often every value appears |
Try it yourself
Show a hint
df["price"]: min(), max() and median().Show the solution
import pandas as pd
df = pd.read_csv("orders.csv")
print(df["price"].min())
print(df["price"].max())
print(df["price"].median())Output
6.8 249.0 35.96
6Choosing rows by position: iloc
iloc works like indexing a NumPy table: df.iloc[rows, columns]. Positions start at 0, and a slice stops before its end.
6.1One row
import pandas as pd
df = pd.read_csv("orders.csv")
row = df.iloc[0]
print(row)
print(row["product"], row["price"])Output
date 2025-01-01 customer Nigar city Baku category Home product Mug price 8.5 units 2 rating 5.0 Name: 0, dtype: object Mug 8.5
Change it and run: print the last row: df.iloc[-1].
One row comes back as a Series. Its labels are the column names, so row["product"] reads one value of the row. Name: 0 is the label of the row, and the type is object because the row mixes text and numbers.
6.2Several rows
print(df.iloc[2:5])
print(df.iloc[[0, 100, 200]])
print(df.iloc[-2:])Output
date customer city category product price units rating
2 2025-01-11 Anar Ganja Books Cookbook 24.9 4 5.0
3 2025-01-13 Gunel Baku Books Cookbook 24.9 2 4.0
4 2025-01-14 Leyla Baku Books Dictionary 29.9 1 3.0
date customer city category product price units rating
0 2025-01-01 Nigar Baku Home Mug 8.50 2 5.0
100 2025-06-05 Lala Baku Tech Power bank 40.50 3 4.0
200 2025-10-01 Sabina Ganja Tech Keyboard 53.91 1 5.0
date customer city category product price units rating
298 2025-12-31 Nigar Baku Sports Football 35.0 2 3.0
299 2025-12-31 Ziya Lankaran Books Textbook 39.9 2 2.0Change it and run: print the rows at the positions 10, 11 and 12.
A slice, a list of positions, and negative positions all work as with arrays. The results are DataFrames.
6.3Rows and columns
print(df.iloc[0:3, 0:2])
print(df.iloc[:3, [4, 5]])
print(df.iloc[0, 4])Output
date customer
0 2025-01-01 Nigar
1 2025-01-03 Ziya
2 2025-01-11 Anar
product price
0 Mug 8.5
1 Jacket 129.0
2 Cookbook 24.9
MugChange it and run: print the last three columns of the first two rows.
Rows first, then columns. df.iloc[0, 4] is one value: row 0, column 4 (the product).
6.4A position that does not exist
print(df.iloc[300])Error
IndexError: single positional indexer is out-of-bounds
The table has 300 rows, so the last position is 299, or -1.
| You write | You get |
|---|---|
df.iloc[0] | the first row, as a Series |
df.iloc[-1] | the last row |
df.iloc[2:5] | the rows at the positions 2, 3, 4 |
df.iloc[[0, 100, 200]] | three chosen rows |
df.iloc[0:3, 0:2] | the first 3 rows of the first 2 columns |
df.iloc[0, 4] | one value |
Try it yourself
Show a hint
df.iloc[150] is one row. A slice stops before its end, so the positions 10 to 12 are 10:13, and the first three columns are 0:3.Show the solution
import pandas as pd
df = pd.read_csv("orders.csv")
print(df.iloc[150])
print(df.iloc[10:13, 0:3])Output
date 2025-08-04
customer Murad
city Baku
category Books
product Dictionary
price 26.91
units 1
rating 5.0
Name: 150, dtype: object
date customer city
10 2025-01-19 Kamran Baku
11 2025-01-21 Lala Baku
12 2025-01-23 Turkan Lankaran7Choosing rows by label: loc
loc uses labels: the row labels from the index, and the names of the columns. The pattern is df.loc[row labels, column names].
7.1A small table with names as labels
import pandas as pd
students = pd.DataFrame(
{"age": [20, 25, 22, 30], "grade": [85.5, 92.0, 78.0, 60.5]},
index=["Aylin", "Murad", "Leyla", "Kamran"],
)
print(students.loc["Murad"])
print(students.loc["Murad", "grade"])
print(students.loc[["Aylin", "Leyla"]])Output
age 25.0
grade 92.0
Name: Murad, dtype: float64
92.0
age grade
Aylin 20 85.5
Leyla 22 78.0Change it and run: print Leyla's age.
students.loc["Murad"] is the row with the label Murad. With a column name after the comma you get one value. The age is shown as 25.0 because a row is one Series, and a Series has one type for all its values.
7.2A slice with labels includes its end
print(students.loc["Murad":"Kamran"])
print(students.iloc[1:3])Output
age grade
Murad 25 92.0
Leyla 22 78.0
Kamran 30 60.5
age grade
Murad 25 92.0
Leyla 22 78.0Change it and run: print the rows from Aylin to Leyla with loc.
loc["Murad":"Kamran"] gives three rows, with Kamran. iloc[1:3] gives two rows, without the position 3.
Choose iloc or loc, then the rows and the columns.
students.iloc[1:3]
| position | age0 | grade1 | city2 | |
|---|---|---|---|---|
| Aylin | 0 | 20 | 85.5 | Baku |
| Murad | 1 | 25 | 92.0 | Ganja |
| Leyla | 2 | 22 | 78.0 | Baku |
| Kamran | 3 | 30 | 60.5 | Shaki |
A DataFrame with 2 rows and 3 columns. The slice goes by positions, so it stops before the position 3.
7.3loc with the orders
In the orders table the row labels are the numbers 0 to 299. Labels and positions look the same here, but loc takes the columns by name, which is easier to read:
df = pd.read_csv("orders.csv")
print(df.loc[0, "product"])
print(df.loc[2:4, ["product", "price"]])
print(df.loc[:2, "customer":"category"])Output
Mug
product price
2 Cookbook 24.9
3 Cookbook 24.9
4 Dictionary 29.9
customer city category
0 Nigar Baku Home
1 Ziya Lankaran Clothing
2 Anar Ganja BooksChange it and run: print the price and the units of the rows 10 to 12.
df.loc[2:4] gives the rows 2, 3 and 4. A slice of column names works too, and it also includes its end: "customer":"category" takes customer, city and category.
7.4When the label and the position are different
After sorting, every row keeps its label, but its position changes:
cheap = df.sort_values("price")
print(cheap.head(3))
print(cheap.iloc[0]["price"])
print(cheap.loc[0, "price"])Output
date customer city category product price units rating 232 2025-11-06 Javid Sumqayit Home Mug 6.8 3 NaN 246 2025-11-16 Ramin Sumqayit Home Mug 6.8 1 5.0 254 2025-11-24 Ramin Sumqayit Home Mug 6.8 4 5.0 6.8 8.5
Change it and run: sort by units instead of price. Which row is at the top now, and where is the label 0?
iloc[0] is the row at the top: the cheapest order. loc[0] is the row with the label 0: the first order of the year, wherever it is now.
Sort the table and watch the two markers: iloc[0] and loc[0].
| place | label | product | price | |
|---|---|---|---|---|
| 0 | 0 | Mug | 8.5 | iloc[0]loc[0] |
| 1 | 3 | Novel | 12.5 | |
| 2 | 2 | Cookbook | 24.9 | |
| 3 | 4 | Jeans | 64.9 | |
| 4 | 1 | Jacket | 129.0 |
d.iloc[0] is the row at the top: Mug. d.loc[0] is the row with the label 0: Mug, wherever it is now.
7.5A column as the row labels: set_index
by_customer = df.set_index("customer")
print(by_customer.head(3))
print(by_customer.loc["Sona", ["date", "product", "price"]])Output
date city category product price units rating
customer
Nigar 2025-01-01 Baku Home Mug 8.5 2 5.0
Ziya 2025-01-03 Lankaran Clothing Jacket 129.0 1 3.0
Anar 2025-01-11 Ganja Books Cookbook 24.9 4 5.0
date product price
customer
Sona 2025-03-10 Headphones 89.9
Sona 2025-12-21 Keyboard 59.9Change it and run: print all orders of "Samir".
set_index makes a column the row labels. A label can appear more than once: loc["Sona"] gives all rows with this label. reset_index() turns the labels back into a normal column.
7.6Changing values with loc
df.loc[0, "units"] = 3
df.loc[1, ["price", "units"]] = [119.0, 2]
print(df.head(3))Output
date customer city category product price units rating 0 2025-01-01 Nigar Baku Home Mug 8.5 3 5.0 1 2025-01-03 Ziya Lankaran Clothing Jacket 119.0 2 3.0 2 2025-01-11 Anar Ganja Books Cookbook 24.9 4 5.0
Change it and run: change the city of row 2 to "Baku".
loc on the left side of = changes the table in memory. The file orders.csv stays as it is until you save with to_csv.
| iloc | loc | |
|---|---|---|
| Uses | positions: 0, 1, 2, ... | row labels and column names |
| The end of a slice | not included | included |
| One row | df.iloc[0] | df.loc[0], students.loc["Murad"] |
| Rows and columns | df.iloc[0:3, 0:2] | df.loc[0:2, ["date", "customer"]] |
| One value | df.iloc[0, 4] | df.loc[0, "product"] |
| Not found | IndexError | KeyError |
Try it yourself
loc, print the product of the order with the label 50. Then print the columns customer and price of the orders with the labels 20 to 23.Show a hint
df.loc[50, "product"] is one value. A loc slice includes its end: df.loc[20:23, ["customer", "price"]].Show the solution
import pandas as pd
df = pd.read_csv("orders.csv")
print(df.loc[50, "product"])
print(df.loc[20:23, ["customer", "price"]])Output
Mug customer price 20 Zahra 35.91 21 Konul 31.41 22 Ramin 45.00 23 Aysel 129.00
8Sorting
8.1By one column
import pandas as pd
df = pd.read_csv("orders.csv")
print(df.sort_values("price").head(3))
print(df.sort_values("price", ascending=False).head(3))Output
date customer city category product price units rating
232 2025-11-06 Javid Sumqayit Home Mug 6.8 3 NaN
246 2025-11-16 Ramin Sumqayit Home Mug 6.8 1 5.0
254 2025-11-24 Ramin Sumqayit Home Mug 6.8 4 5.0
date customer city category product price units rating
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
120 2025-06-27 Aysel Baku Tech Smartwatch 249.0 1 5.0Change it and run: sort by units, the largest first.
sort_values sorts from small to large. With ascending=False the largest values come first. Sorting and head together answer "which are the top ...?".
8.2Sorting gives a new table
df.sort_values("price")
print(df.head(2))
df = df.sort_values("price")
print(df.head(2))Output
date customer city category product price units rating
0 2025-01-01 Nigar Baku Home Mug 8.5 2 5.0
1 2025-01-03 Ziya Lankaran Clothing Jacket 129.0 1 3.0
date customer city category product price units rating
232 2025-11-06 Javid Sumqayit Home Mug 6.8 3 NaN
246 2025-11-16 Ramin Sumqayit Home Mug 6.8 1 5.0sort_values does not change df. It gives a sorted copy, and you must store it. Most pandas methods work this way.
8.3By two columns
df = pd.read_csv("orders.csv")
by_city = df.sort_values(["city", "price"], ascending=[True, False])
print(by_city[["city", "product", "price"]].head(4))Output
city product price 120 Baku Smartwatch 249.0 280 Baku Smartwatch 249.0 265 Baku Smartwatch 224.1 23 Baku Jacket 129.0
Change it and run: sort the prices inside every city from low to high: ascending=[True, True].
First by city from A to Z, and inside every city by price, the most expensive first. Text is sorted by the alphabet.
8.4The largest and the smallest: nlargest and nsmallest
print(df.nlargest(3, "units")[["customer", "product", "units"]])
print(df.nsmallest(2, "price")[["product", "price"]])Output
customer product units 31 Leyla Cookbook 5 44 Javid Novel 5 55 Zahra Novel 5 product price 12 Mug 6.8 17 Mug 6.8
Change it and run: print the 3 orders with the lowest rating.
nlargest(3, "units") is a short way for "sort by units, largest first, and take 3".
8.5New row labels after sorting
top = df.sort_values("price", ascending=False).reset_index(drop=True)
print(top[["product", "price"]].head(3))Output
product price 0 Smartwatch 249.0 1 Smartwatch 249.0 2 Smartwatch 249.0
Change it and run: remove .reset_index(drop=True). The old labels come back.
reset_index(drop=True) numbers the rows again from 0, so label and position are the same again. sort_index() does the opposite: it sorts the rows by their labels, back into the old order.
| You write | You get |
|---|---|
df.sort_values("price") | sorted by price, the smallest first |
df.sort_values("price", ascending=False) | the largest first |
df.sort_values(["city", "price"]) | by city, and inside every city by price |
df.nlargest(3, "price") | the 3 rows with the highest price |
df.nsmallest(3, "price") | the 3 rows with the lowest price |
df.reset_index(drop=True) | the same rows with new labels 0, 1, 2, ... |
df.sort_index() | sorted by the row labels |
Try it yourself
customer from A to Z, and the orders of one customer by price, the most expensive first. Print the columns customer, product and price of the first 3 rows.Show a hint
df.sort_values(["customer", "price"], ascending=[True, False]), then choose the three columns and take .head(3).Show the solution
import pandas as pd
df = pd.read_csv("orders.csv")
ordered = df.sort_values(["customer", "price"], ascending=[True, False])
print(ordered[["customer", "product", "price"]].head(3))Output
customer product price 68 Aida Smartwatch 249.00 98 Aida Headphones 80.91 6 Aida Keyboard 53.91
9New columns and changing columns
9.1A new column from a calculation
The money of an order is the price times the units. Columns calculate like NumPy arrays, row by row, without a loop:
import pandas as pd
df = pd.read_csv("orders.csv")
df["total"] = df["price"] * df["units"]
print(df[["product", "price", "units", "total"]].head())
print(round(df["total"].sum(), 2))Output
product price units total 0 Mug 8.5 2 17.0 1 Jacket 129.0 1 129.0 2 Cookbook 24.9 4 99.6 3 Cookbook 24.9 2 49.8 4 Dictionary 29.9 1 29.9 21935.22
Change it and run: add a second column: df["half"] = df["total"] / 2, and print it too.
A new name in the square brackets on the left of = creates the column. The last line is the money of the whole year.
df["total"] = df["price"] * df["units"]
| price | units | total | |
|---|---|---|---|
| 0 | 8.5 | 2 | 17.0 |
| 1 | 129.0 | 1 | 129.0 |
| 2 | 24.9 | 4 | 99.6 |
9.2When a table is too wide
df = pd.read_csv("orders.csv")
df["total"] = df["price"] * df["units"]
print(df.head(3))Output
date customer city category ... price units rating total 0 2025-01-01 Nigar Baku Home ... 8.5 2 5.0 17.0 1 2025-01-03 Ziya Lankaran Clothing ... 129.0 1 3.0 129.0 2 2025-01-11 Anar Ganja Books ... 24.9 4 5.0 99.6 [3 rows x 9 columns]
Change it and run: add pd.set_option("display.width", 200) as the second line. All nine columns are shown.
With nine columns a row is longer than 80 characters, so pandas shortens the table: ... stands for the columns in the middle, and the last line gives the real size. (In a Jupyter notebook, print shows such a table in two pieces instead, one under the other.) Print only the columns you need, as in the example before, or allow longer lines with pd.set_option("display.width", 200).
9.3More new columns
df = pd.read_csv("orders.csv")
df["currency"] = "AZN"
df["price_usd"] = (df["price"] / 1.7).round(2)
print(df[["product", "price", "currency", "price_usd"]].head(3))Output
product price currency price_usd 0 Mug 8.5 AZN 5.00 1 Jacket 129.0 AZN 75.88 2 Cookbook 24.9 AZN 14.65
Change it and run: change the rate from 1.7 to 2.
One value is put into every row. A calculation can use numbers and other columns, and .round(2) rounds every value of a column.
9.4Changing a column
df = pd.read_csv("orders.csv")
df["rating"] = df["rating"] * 20
print(df[["product", "rating"]].head(3))Output
product rating 0 Mug 100.0 1 Jacket 60.0 2 Cookbook 100.0
Change it and run: turn the prices into qepik: df["price"] = df["price"] * 100.
A name that already exists is replaced: the ratings from 1 to 5 are now points from 20 to 100.
9.5Renaming columns
df = pd.read_csv("orders.csv")
df = df.rename(columns={"units": "quantity", "price": "unit_price"})
print(df.columns.tolist())Output
['date', 'customer', 'city', 'category', 'product', 'unit_price', 'quantity', 'rating']
Change it and run: rename date to day as well.
rename takes a dictionary: old name, new name.
9.6Removing columns
df = pd.read_csv("orders.csv")
df = df.drop(columns=["date", "rating"])
print(df.head(3))Output
customer city category product price units 0 Nigar Baku Home Mug 8.5 2 1 Ziya Lankaran Clothing Jacket 129.0 1 2 Anar Ganja Books Cookbook 24.9 4
Change it and run: remove only the column category.
9.7Converting a type: astype
df = pd.read_csv("orders.csv")
df["units"] = df["units"].astype(float)
df["price"] = df["price"].astype(int)
print(df[["product", "price", "units"]].head(3))Output
product price units 0 Mug 8 2.0 1 Jacket 129 1.0 2 Cookbook 24 4.0
units is now a decimal, and price a whole number. As in NumPy, astype(int) cuts off the decimals. It does not round.
9.8A copy of a table
df = pd.read_csv("orders.csv")
backup = df.copy()
df["price"] = 0
print(df["price"].head(2).tolist())
print(backup["price"].head(2).tolist())Output
[0, 0] [8.5, 129.0]
Change it and run: replace df.copy() with df and run it again. Both lines print zeros: it was the same table.
df.copy() is a separate table. Make one before you change data that you may still need.
| You write | What it does |
|---|---|
df["total"] = df["price"] * df["units"] | a new column from a calculation |
df["currency"] = "AZN" | a new column with one value in every row |
df["rating"] = df["rating"] * 20 | replaces a column |
df = df.rename(columns={"units": "quantity"}) | renames a column |
df = df.drop(columns=["date"]) | removes a column |
df["units"] = df["units"].astype(float) | changes the type of a column |
backup = df.copy() | a separate copy of the table |
Try it yourself
price_with_tax: the price times 1.18, rounded to 2 decimals. Print the columns product, price and price_with_tax of the first 3 rows.Show a hint
df["price_with_tax"] = (df["price"] * 1.18).round(2). Then choose the three columns with double brackets.Show the solution
import pandas as pd
df = pd.read_csv("orders.csv")
df["price_with_tax"] = (df["price"] * 1.18).round(2)
print(df[["product", "price", "price_with_tax"]].head(3))Output
product price price_with_tax 0 Mug 8.5 10.03 1 Jacket 129.0 152.22 2 Cookbook 24.9 29.38
10Common 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.
A wrong column name: df["City"]
Wrong
import pandas as pd
df = pd.read_csv("orders.csv")
print(df["City"])KeyError: 'City'
Right
import pandas as pd
df = pd.read_csv("orders.csv")
print(df["city"].head(3).tolist())
# prints: ['Baku', 'Lankaran', 'Ganja']KeyError: 'City'. Names are case-sensitive: look at df.columns.
df["city", "price"]
Wrong
import pandas as pd
df = pd.read_csv("orders.csv")
print(df["city", "price"])KeyError: ('city', 'price')Right
import pandas as pd
df = pd.read_csv("orders.csv")
print(df[["city", "price"]].shape)
# prints: (300, 2)KeyError. A list inside the brackets: df[["city", "price"]].
df[0] for the first row
Wrong
import pandas as pd
df = pd.read_csv("orders.csv")
print(df[0])KeyError: 0
Right
import pandas as pd
df = pd.read_csv("orders.csv")
print(df.iloc[0]["product"])
# prints: MugKeyError: 0. Square brackets alone look for a column. Use df.iloc[0].
A column name inside iloc
Wrong
import pandas as pd
df = pd.read_csv("orders.csv")
print(df.iloc[0, "city"])ValueError: Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types
Right
import pandas as pd
df = pd.read_csv("orders.csv")
print(df.loc[0, "city"])
# prints: BakuValueError. iloc takes positions, loc takes names.
Forgetting that a loc slice includes its end
Wrong
import pandas as pd
df = pd.read_csv("orders.csv")
# the first four rows
print(len(df.loc[0:4]))
# prints: 5Right
import pandas as pd
df = pd.read_csv("orders.csv")
# the first four rows
print(len(df.iloc[0:4]))
# prints: 4One row too many. df.loc[0:4] is 5 rows, df.iloc[0:4] is 4.
A position that does not exist: df.iloc[300]
Wrong
print(df.iloc[300])
IndexError: single positional indexer is out-of-bounds
Right
import pandas as pd
df = pd.read_csv("orders.csv")
print(df.iloc[-1]["product"])
# prints: TextbookIndexError. The last position is len(df) - 1, or -1.
df.sort_values("price") without storing it
Wrong
import pandas as pd
df = pd.read_csv("orders.csv")
df.sort_values("price")
print(df.iloc[0]["price"])
# prints: 8.5Right
import pandas as pd
df = pd.read_csv("orders.csv")
df = df.sort_values("price")
print(df.iloc[0]["price"])
# prints: 6.8df is not sorted. Write df = df.sort_values("price").
to_csv without index=False
Wrong
import pandas as pd
df = pd.read_csv("orders.csv")
df.head(3).to_csv("copy.csv")
print(pd.read_csv("copy.csv").columns.tolist()[:3])
# prints: ['Unnamed: 0', 'date', 'customer']Right
import pandas as pd
df = pd.read_csv("orders.csv")
df.head(3).to_csv("copy.csv", index=False)
print(pd.read_csv("copy.csv").columns.tolist()[:3])
# prints: ['date', 'customer', 'city']An extra column Unnamed: 0 when the file is read again. Write to_csv("name.csv", index=False).
A wrong column name:
import pandas as pd
df = pd.read_csv("orders.csv")
print(df["City"])Error
KeyError: 'City'
Several columns without the inner list:
import pandas as pd
df = pd.read_csv("orders.csv")
print(df["city", "price"])Error
KeyError: ('city', 'price')The first row with square brackets alone:
import pandas as pd
df = pd.read_csv("orders.csv")
print(df[0])Error
KeyError: 0
Square brackets alone look for a column with the name 0. Rows need iloc or loc.
A column name inside iloc:
import pandas as pd
df = pd.read_csv("orders.csv")
print(df.iloc[0, "city"])Error
ValueError: Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types
Saving without index=False:
import pandas as pd
df = pd.read_csv("orders.csv")
df.head(3).to_csv("copy.csv")
print(pd.read_csv("copy.csv").iloc[:, :4])Output
Unnamed: 0 date customer city 0 0 2025-01-01 Nigar Baku 1 1 2025-01-03 Ziya Lankaran 2 2 2025-01-11 Anar Ganja
The old row labels were saved as a column without a name, and pandas calls it Unnamed: 0.
11Solved problems (easy to medium-hard)
Every example was run, and the outputs are real.
11.1Level 1: Easy
Problem 1: The warmest day
import pandas as pd
temps = pd.Series([18, 22, 25, 19, 16], index=["Mon", "Tue", "Wed", "Thu", "Fri"])
print(temps["Wed"])
print(temps.idxmax(), temps.max())
print(temps.mean())Output
25 Wed 25 20.0
Change it and run: add the temperature 27 for Sat.
Problem 2: A small table
import pandas as pd
df = pd.DataFrame({
"city": ["Baku", "Ganja", "Shaki"],
"population": [2300000, 335000, 68000],
})
print(df)
print(df.shape)
print(df["population"].sum())Output
city population 0 Baku 2300000 1 Ganja 335000 2 Shaki 68000 (3, 2) 2703000
Change it and run: add a fourth city of your choice.
Problem 3: Read the file and look at its size
import pandas as pd
df = pd.read_csv("orders.csv")
print("Rows:", df.shape[0])
print("Columns:", df.shape[1])
print(df.columns.tolist())Output
Rows: 300 Columns: 8 ['date', 'customer', 'city', 'category', 'product', 'price', 'units', 'rating']
Problem 4: The first and the last orders
import pandas as pd
df = pd.read_csv("orders.csv")
print(df.head(3))
print(df.tail(2))Output
date customer city category product price units rating
0 2025-01-01 Nigar Baku Home Mug 8.5 2 5.0
1 2025-01-03 Ziya Lankaran Clothing Jacket 129.0 1 3.0
2 2025-01-11 Anar Ganja Books Cookbook 24.9 4 5.0
date customer city category product price units rating
298 2025-12-31 Nigar Baku Sports Football 35.0 2 3.0
299 2025-12-31 Ziya Lankaran Books Textbook 39.9 2 2.0Change it and run: print the first 10 rows.
Problem 5: How many orders in each category?
import pandas as pd
df = pd.read_csv("orders.csv")
print(df["category"].value_counts())Output
category Books 74 Tech 68 Home 56 Clothing 54 Sports 48 Name: count, dtype: int64
Change it and run: count the cities instead.
11.2Level 2: Medium
Problem 6: The most expensive order
import pandas as pd
df = pd.read_csv("orders.csv")
top = df.sort_values("price", ascending=False).iloc[0]
print(top["customer"], "bought a", top["product"], "for", top["price"])Output
Ramin bought a Smartwatch for 249.0
Change it and run: find the cheapest order instead.
Why: after sorting with the largest first, the row at the position 0 is the most expensive one. It is a Series, so the column names reach its values.
Problem 7: Five rows and three columns
import pandas as pd
df = pd.read_csv("orders.csv")
print(df.loc[100:104, ["customer", "product", "price"]])Output
customer product price 100 Lala Power bank 40.5 101 Vusal Smartwatch 249.0 102 Aylin Jeans 64.9 103 Ruslan Football 35.0 104 Konul T-shirt 19.9
Change it and run: print the rows 200 to 203.
Why: loc takes the columns by name, and its slice includes the end: 100 to 104 are five rows.
Problem 8: The money of every order
import pandas as pd
df = pd.read_csv("orders.csv")
df["total"] = df["price"] * df["units"]
print("Revenue:", round(df["total"].sum(), 2))
print("Average order:", round(df["total"].mean(), 2))
print("Largest order:", df["total"].max())Output
Revenue: 21935.22 Average order: 73.12 Largest order: 448.2
Change it and run: print the smallest order too: df["total"].min().
Problem 9: The five largest orders
import pandas as pd
df = pd.read_csv("orders.csv")
df["total"] = df["price"] * df["units"]
top = df.sort_values("total", ascending=False).head(5)
print(top[["customer", "product", "units", "total"]])Output
customer product units total 171 Ramin Smartwatch 2 448.2 101 Vusal Smartwatch 1 249.0 120 Aysel Smartwatch 1 249.0 280 Lala Smartwatch 1 249.0 277 Sabina Smartwatch 1 249.0
Change it and run: print the ten largest orders.
Why: first the new column, then sorting by it, then head. The row labels on the left show where these orders are in the file.
Problem 10: The customers
import pandas as pd
df = pd.read_csv("orders.csv")
print("Customers:", df["customer"].nunique())
print(df["customer"].value_counts().head(3))Output
Customers: 40 customer Ramin 28 Murad 24 Aylin 18 Name: count, dtype: int64
Change it and run: print the five customers who ordered most often.
Why: nunique counts the different names. value_counts puts the most frequent customers first, so head(3) gives the top three.
11.3Level 3: Medium-Hard
Problem 11: One order, chosen by the user
import pandas as pd
df = pd.read_csv("orders.csv")
position = int(input("Row number: "))
row = df.iloc[position]
print(row["date"], row["customer"], row["product"])
print("Total:", row["price"] * row["units"])Output
Row number: 42 2025-03-11 Murad Pillow Total: 17.6
Change it and run: run it with other row numbers, for example 0 and 299.
Why: iloc gives the row as a Series, and its values are reached with the column names.
Problem 12: Sorted by city, then by price
import pandas as pd
df = pd.read_csv("orders.csv")
ordered = df.sort_values(["city", "price"], ascending=[True, False])
print(ordered[["city", "product", "price"]].head(6))Output
city product price 120 Baku Smartwatch 249.0 280 Baku Smartwatch 249.0 265 Baku Smartwatch 224.1 23 Baku Jacket 129.0 153 Baku Jacket 129.0 210 Baku Jacket 129.0
Change it and run: sort the cities from Z to A.
Problem 13: How many orders have a rating?
import pandas as pd
df = pd.read_csv("orders.csv")
rated = df["rating"].count()
print("With a rating:", rated)
print("Without a rating:", len(df) - rated)
print("Average rating:", round(df["rating"].mean(), 2))Output
With a rating: 264 Without a rating: 36 Average rating: 4.06
Change it and run: do the same for the column city.
Why: count skips the missing values, and len counts all rows. The difference is the number of missing ratings.
Problem 14: Save the ten largest orders
import pandas as pd
df = pd.read_csv("orders.csv")
df["total"] = df["price"] * df["units"]
top = df.sort_values("total", ascending=False).head(10)
top[["date", "customer", "product", "total"]].to_csv("top_orders.csv", index=False)
check = pd.read_csv("top_orders.csv")
print(check.shape)
print(check.head(3))Output
(10, 4)
date customer product total
0 2025-08-31 Ramin Smartwatch 448.2
1 2025-06-05 Vusal Smartwatch 249.0
2 2025-06-27 Aysel Smartwatch 249.0Change it and run: save only the three largest orders.
Why: the columns are chosen before saving, and index=False keeps the old row labels out of the file. Reading the file again shows that it holds 10 rows and 4 columns.
Problem 15: A report about a column
import pandas as pd
def column_report(df, column):
values = df[column]
print(column, "| min:", values.min(), "| max:", values.max(), "| mean:", round(values.mean(), 2))
df = pd.read_csv("orders.csv")
for column in ["price", "units", "rating"]:
column_report(df, column)Output
price | min: 6.8 | max: 249.0 | mean: 50.64 units | min: 1 | max: 5 | mean: 1.73 rating | min: 1.0 | max: 5.0 | mean: 4.06
Change it and run: add "total" to the list of columns: first create the column, as in problem 8.
Why: the function gets the table and a column name, so the same lines work for every number column.
12Practice problems (try them yourself)
Fifteen problems in three levels. They work like one notebook: the setup cell below reads the file, and every problem is a cell that continues from it. So you do not write import pandas as pd and pd.read_csv again: df is already there.
import pandas as pd
df = pd.read_csv("orders.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
A first look at the table, one column and counting.
- 1.Print the first 7 rows of the orders table.
Show a hint
df.head()gives 5 rows. A number in the parentheses changes how many.Show one possible solution
Python, continues from the cells aboveprint(df.head(7))Output
date customer city category product price units rating 0 2025-01-01 Nigar Baku Home Mug 8.50 2 5.0 1 2025-01-03 Ziya Lankaran Clothing Jacket 129.00 1 3.0 2 2025-01-11 Anar Ganja Books Cookbook 24.90 4 5.0 3 2025-01-13 Gunel Baku Books Cookbook 24.90 2 4.0 4 2025-01-14 Leyla Baku Books Dictionary 29.90 1 3.0 5 2025-01-15 Elvin Baku Clothing Jeans 64.90 1 4.0 6 2025-01-15 Aida Sumqayit Tech Keyboard 53.91 1 4.0
- 2.Print the column names of the orders table as a list, and the number of rows. Two lines.
Show a hint
df.columns.tolist()gives the names as a list. The number of rows islen(df).Show one possible solution
Python, continues from the cells aboveprint(df.columns.tolist()) print(len(df))Output
['date', 'customer', 'city', 'category', 'product', 'price', 'units', 'rating'] 300
- 3.Print the
customercolumn of the last 4 orders.Show a hint
Choose the column first,df["customer"], then take its end with.tail(4).Show one possible solution
Python, continues from the cells aboveprint(df["customer"].tail(4))Output
296 Leyla 297 Konul 298 Nigar 299 Ziya Name: customer, dtype: str
- 4.Print how many orders each city has.
Show a hint
value_counts()on the columncitycounts how often every city appears.Show one possible solution
Python, continues from the cells aboveprint(df["city"].value_counts())Output
city Baku 128 Ganja 54 Sumqayit 48 Quba 30 Lankaran 22 Shaki 10 Name: count, dtype: int64
Medium
Rows by position and by label, the largest values and a new column.
- 5.Read a number
n. Print the product and the price of the order at the positionn, on one line.Examples:42givesPillow 17.60givesMug 8.5299givesTextbook 39.9Show a hint
df.iloc[n]gives the row as a Series. Read its values with the column names:row["product"],row["price"].Show one possible solution
Python, continues from the cells aboven = int(input()) row = df.iloc[n] print(row["product"], row["price"])Output
Pillow 17.6
- 6.Print the rows at the positions 50 to 54 with the columns
date,productandunits.Show a hint
Withlocthe columns go in by name and the slice includes its end:df.loc[50:54, [...]]. Withilocthe slice is50:55, and the columns are chosen afterwards.Show one possible solution
Python, continues from the cells aboveprint(df.loc[50:54, ["date", "product", "units"]])Output
date product units 50 2025-03-19 Mug 3 51 2025-03-20 Power bank 1 52 2025-03-21 Smartwatch 1 53 2025-03-23 Dumbbells 1 54 2025-03-26 Dictionary 1
- 7.Find the three orders with the highest price. Print the products of these orders as a list, then their prices as a list.
Show a hint
df.nlargest(3, "price")gives the three rows. Store them, then printtop["product"].tolist()andtop["price"].tolist().Show one possible solution
Python, continues from the cells abovetop = df.nlargest(3, "price") print(top["product"].tolist()) print(top["price"].tolist())Output
['Smartwatch', 'Smartwatch', 'Smartwatch'] [249.0, 249.0, 249.0]
- 8.Read the name of a category. Print how many orders this category has.Examples:
Booksgives74Techgives68Homegives56Show a hint
df["category"].value_counts()is a Series, and the categories are its labels. Reach one count with the label:counts[category].Show one possible solution
Python, continues from the cells abovecategory = input() counts = df["category"].value_counts() print(counts[category])Output
74
- 9.Add a column
total(price times units). Print the largest total and the name of the customer who made that order. Two lines.Show a hint
df["total"] = df["price"] * df["units"]. The largest value is.max(), and.idxmax()gives the label of its row. With the label,df.loc[label, "customer"]is the name.Show one possible solution
Python, continues from the cells abovedf["total"] = df["price"] * df["units"] print(df["total"].max()) print(df.loc[df["total"].idxmax(), "customer"])Output
448.2 Ramin
Medium-Hard
Sorting by two columns, row labels, saving a file and a function.
- 10.Sort the orders by
units, the largest first, and orders with the same number of units byprice, the largest first. Print the first 4 rows with the columnsproduct,unitsandprice.Show a hint
Two columns in a list, and a list for the directions:df.sort_values(["units", "price"], ascending=[False, False]). Then choose the three columns and take.head(4).Show one possible solution
Python, continues from the cells aboveordered = df.sort_values(["units", "price"], ascending=[False, False]) print(ordered[["product", "units", "price"]].head(4))Output
product units price 93 Football 5 28.00 58 Yoga mat 5 27.90 264 Cookbook 5 24.90 31 Cookbook 5 19.92
- 11.Make the customer names the row labels with
set_indexand store the result inby_customer. Print the columnsdate,productandpriceof all orders of the customerSona.Show a hint
by_customer = df.set_index("customer"). Thenby_customer.loc["Sona", [...]]gives every row with this label.Show one possible solution
Python, continues from the cells aboveby_customer = df.set_index("customer") print(by_customer.loc["Sona", ["date", "product", "price"]])Output
date product price customer Sona 2025-03-10 Headphones 89.9 Sona 2025-12-21 Keyboard 59.9
- 12.This problem continues from Problem 9: the table already has the column
totalfrom your answer there. Save the columnsdate,productandtotalinto the filetotals.csvwithout the row labels. Read the new file and print itsshapeand its first 3 rows.Show a hint
Choose the three columns with double brackets, then.to_csv("totals.csv", index=False). Read the file withpd.read_csvinto a new variable. If Python says there is no columntotal, finish Problem 9 first.Show one possible solution
Python, continues from the cells abovedf[["date", "product", "total"]].to_csv("totals.csv", index=False) check = pd.read_csv("totals.csv") print(check.shape) print(check.head(3))Output
(300, 3) date product total 0 2025-01-01 Mug 17.0 1 2025-01-03 Jacket 129.0 2 2025-01-11 Cookbook 99.6 - 13.Print the share of every category in the orders, in percent, rounded to 1 decimal.
Show a hint
value_counts(normalize=True)gives shares between 0 and 1. Multiply by 100, then.round(1).Show one possible solution
Python, continues from the cells aboveshares = df["category"].value_counts(normalize=True) * 100 print(shares.round(1))Output
category Books 24.7 Tech 22.7 Home 18.7 Clothing 18.0 Sports 16.0 Name: proportion, dtype: float64
- 14.Write a function
top_products(df, n)that returns thenmost often ordered products as a list.Examples:3gives['Dictionary', 'Cookbook', 'Keyboard']1gives['Dictionary']4gives['Dictionary', 'Cookbook', 'Keyboard', 'Headphones']Show a hint
df["product"].value_counts()has the most frequent product first. Take.head(n). The products are the labels of this Series:.index.tolist().Show one possible solution
Python, continues from the cells abovedef top_products(df, n): counts = df["product"].value_counts() return counts.head(n).index.tolist() n = int(input()) print(top_products(df, n))Output
['Dictionary', 'Cookbook', 'Keyboard']
- 15.Work on a copy of the table,
shop, so thatdfstays as it is. In the copy, renameunitstoquantity, remove the columnrating, and add a columnprice_usd: the price divided by 1.7, rounded to 2 decimals. Print the columnsproduct,price,quantityandprice_usdof the first 3 rows.Show a hint
rename(columns={...})anddrop(columns=[...])give new tables: store them back inshop. The new column:shop["price_usd"] = (shop["price"] / 1.7).round(2).Show one possible solution
Python, continues from the cells aboveshop = df.copy() shop = shop.rename(columns={"units": "quantity"}) shop = shop.drop(columns=["rating"]) shop["price_usd"] = (shop["price"] / 1.7).round(2) print(shop[["product", "price", "quantity", "price_usd"]].head(3))Output
product price quantity price_usd 0 Mug 8.5 2 5.00 1 Jacket 129.0 1 75.88 2 Cookbook 24.9 4 14.65
13Check 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.
14Quick summary
| Concept | What it does | Example |
|---|---|---|
import pandas as pd | loads pandas | pd.read_csv("orders.csv") |
| Series | one column of values with labels | pd.Series([85, 92], index=["Aylin", "Murad"]) |
| DataFrame | a table of columns | pd.DataFrame({"name": [...], "age": [...]}) |
read_csv / to_csv | reads / saves a CSV file | df.to_csv("new.csv", index=False) |
head / tail | the first / last rows | df.head(3) |
shape / dtypes | size / type of every column | df.shape |
info / describe | a summary / statistics | df.info() |
| One column | a Series | df["price"] |
| Several columns | a DataFrame | df[["product", "price"]] |
unique / nunique / value_counts | different values / how many / how often | df["city"].value_counts() |
iloc | rows and columns by position | df.iloc[0:3, 0:2] |
loc | rows and columns by label | df.loc[0:2, ["date", "price"]] |
set_index / reset_index | a column as row labels / back | df.set_index("customer") |
sort_values | sorts by a column | df.sort_values("price", ascending=False) |
nlargest / nsmallest | the top / bottom rows | df.nlargest(3, "price") |
| New column | a calculation with whole columns | df["total"] = df["price"] * df["units"] |
rename / drop | renames / removes columns | df.drop(columns=["rating"]) |