Asiman Data School

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

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. 1.What pandas is, and what a Series and a DataFrame are
  2. 2.Creating a Series, and reaching its values by label and by position
  3. 3.Creating a DataFrame from a dictionary
  4. 4.Reading a CSV file with read_csv, and saving one with to_csv
  5. 5.A first look at a table: head, tail, shape, dtypes, info, describe
  6. 6.Choosing columns, and summaries of a column: mean, unique, value_counts
  7. 7.Choosing rows with iloc (by position) and loc (by label)
  8. 8.Sorting with sort_values
  9. 9.New columns, renaming and removing columns
  10. 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:

Python
import pandas as pd

print(pd.__version__)

Output

3.0.2

1.2Two building blocks

Two building blocks
What it isThink of it as
Seriesone column of values, and every value has a labelone column of a spreadsheet
DataFramea table: several columns side by sidethe whole spreadsheet

A DataFrame is made of Series: every column of a DataFrame is a Series.

1.3Why not just a NumPy array?

Why not just a NumPy array?
NumPy arraypandas DataFrame
Typesone type for all itemsevery column has its own type
Rows and columnsreached by positionhave names (labels)
Made fornumbers and calculationreal data: names, dates, prices, gaps
Reading filesnot its jobone 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

Python, continues from the cells above
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

Python, continues from the cells above
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

Aylin85
Murad92
Leyla78
Kamran60

dtype: int64

A Series is one column of values. Every value has a label, and all labels together are the index. The values share one type.

1.6A Series from a dictionary

The keys become the labels:

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
print(grades["Nigar"])

Error

KeyError: 'Nigar'

in checks whether a label exists: "Nigar" in grades gives False.

1.11Changing and adding values

Python, continues from the cells above
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.

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
print(grades.tolist())
print(grades.to_numpy())

Output

[85, 92, 78, 60]
[85 92 78 60]
From a Series to a list or an array
You writeYou 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

Create a Series 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
Python
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:

Python
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.

nameagegrade
0Aylin2085.5
1Murad2592.0
2Leyla2278.0
3Kamran3060.5
  • Columns: the names on top.
  • Index: the row labels on the left, here 0 to 3.
  • Values: everything inside.
Every column is a Series with the same index. The marked column is 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

Python, continues from the cells above
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

Python, continues from the cells above
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.)

The properties of a DataFrame
dtypeMeaning
int64whole numbers
float64decimals
strtext (older pandas versions show object here)
boolTrue and False
datetime64dates (Part 3)

2.4Every column is a Series

Python, continues from the cells above
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:

Python, continues from the cells above
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:

Python, continues from the cells above
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

From the two lists, create a DataFrame with the columns name and age. Print its shape and the mean age.
Show a hint
A dictionary with two keys: pd.DataFrame({"name": names, "age": ages}). The mean age is the mean of the column age.
Show the solution
Python
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:

Python
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.

Download

Loading the table ...

3.3The columns of orders.csv

The columns of orders.csv
ColumnMeaningExample
datethe day of the order2025-01-03
customerthe first name of the customerZiya
citythe city of the customerLankaran
categorythe product group: Tech, Clothing, Books, Home or SportsClothing
productwhat was boughtJacket
pricethe price of one unit, in AZN129.00
unitshow many units were bought1
ratingthe customer's rating from 1 to 5 (some customers gave none)3

3.4Useful options of read_csv

Useful options of read_csv
OptionWhat it doesExample
usecolsreads only some columnsusecols=["date", "price"]
nrowsreads only the first rowsnrows=100
septhe separator, if it is not a commasep=";"
index_coluses a column as the row labelsindex_col="date"
parse_datesreads a column as real datesparse_dates=["date"]
Python, continues from the cells above
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:

Python, continues from the cells above
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:

Python
import pandas as pd

df = pd.read_excel("orders.xlsx")

3.7Saving a table: to_csv

Python, continues from the cells above
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

Read only the columns customer, city and price of orders.csv, and only the first 5 rows. Print the table.
Show a hint
Two options of read_csv: usecols=[...] for the columns and nrows=5 for the rows.
Show the solution
Python
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

Python
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.0

Change 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

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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.

describe: statistics of the number columns
RowMeaning
counthow many values are not missing
meanthe average
stdthe standard deviation: how spread out the values are (you will meet it in the statistics lessons)
min, maxthe 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.

describe: statistics of the number columns
You writeYou see
df.head(), df.tail()the first / last 5 rows
df.shape(rows, columns)
df.columns.tolist()the column names as a list
df.dtypesthe type of every column
df.info()names, missing values and types in one summary
df.describe()statistics of the number columns

Try it yourself

Print the last 4 rows of the orders table, then the number of rows.
Show a hint
df.tail(4) and len(df).
Show the solution
Python
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

Python
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

Python, continues from the cells above
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?

Python, continues from the cells above
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,)

08.5
1129.0
224.9

df[["product", "price"]]

A DataFrame: two dimensions, shape (300, 2)

productprice
0Mug8.5
1Jacket129.0
2Cookbook24.9
The outer brackets choose columns. One name gives one column. A list of names, even a list with one name, gives a table.

5.4The short way with a dot

df.price means the same as df["price"]:

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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:

Python, continues from the cells above
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

Python, continues from the cells above
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.

Shares instead of counts
You writeYou 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

Print the lowest price, the highest price and the median price, each on its own line.
Show a hint
Three methods of the column df["price"]: min(), max() and median().
Show the solution
Python
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

Python
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

Python, continues from the cells above
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.0

Change 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

Python, continues from the cells above
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
Mug

Change 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

Python, continues from the cells above
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.

A position that does not exist
You writeYou 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

Print the row at the position 150. Then print the rows at the positions 10 to 12 with the first three columns.
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
Python
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  Lankaran

7Choosing 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

Python
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.0

Change 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

Python, continues from the cells above
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.0

Change 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.

rows
columns
students.iloc[1:3]
The students table; the chosen cells are highlighted
positionage0grade1city2
Aylin02085.5Baku
Murad12592.0Ganja
Leyla22278.0Baku
Kamran33060.5Shaki

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:

Python, continues from the cells above
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     Books

Change 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:

Python, continues from the cells above
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].

Five orders in the chosen order, with the position and the label of every row
placelabelproductprice
00Mug8.5iloc[0]loc[0]
13Novel12.5
22Cookbook24.9
34Jeans64.9
41Jacket129.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

Python, continues from the cells above
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.9

Change 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

Python, continues from the cells above
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.

Changing values with loc
ilocloc
Usespositions: 0, 1, 2, ...row labels and column names
The end of a slicenot includedincluded
One rowdf.iloc[0]df.loc[0], students.loc["Murad"]
Rows and columnsdf.iloc[0:3, 0:2]df.loc[0:2, ["date", "customer"]]
One valuedf.iloc[0, 4]df.loc[0, "product"]
Not foundIndexErrorKeyError

Try it yourself

With 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
Python
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

Python
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.0

Change 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

Python, continues from the cells above
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.0

sort_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

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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.

New row labels after sorting
You writeYou 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

Sort the orders by 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
Python
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:

Python
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"]

priceunitstotal
08.5217.0
1129.01129.0
224.9499.6
The calculation is done for every row: 8.5 × 2, 129.0 × 1, 24.9 × 4. The results become the new column, with the same row labels.

9.2When a table is too wide

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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.

A copy of a table
You writeWhat 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"] * 20replaces 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

Add a column 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
Python
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: Mug

KeyError: 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: Baku

ValueError. 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: 5

Right

import pandas as pd

df = pd.read_csv("orders.csv")
# the first four rows
print(len(df.iloc[0:4]))

# prints: 4

One 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: Textbook

IndexError. 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.5

Right

import pandas as pd

df = pd.read_csv("orders.csv")
df = df.sort_values("price")
print(df.iloc[0]["price"])

# prints: 6.8

df 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:

Python
import pandas as pd

df = pd.read_csv("orders.csv")
print(df["City"])

Error

KeyError: 'City'

Several columns without the inner list:

Python
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:

Python
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:

Python
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:

Python
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

Python
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

Python
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

Python
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

Python
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.0

Change it and run: print the first 10 rows.

Problem 5: How many orders in each category?

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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?

Python
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

Python
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.0

Change 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

Python
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.

Python
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. 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 above
    print(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. 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 is len(df).
    Show one possible solution
    Python, continues from the cells above
    print(df.columns.tolist())
    print(len(df))

    Output

    ['date', 'customer', 'city', 'category', 'product', 'price', 'units', 'rating']
    300
  3. 3.Print the customer column 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 above
    print(df["customer"].tail(4))

    Output

    296    Leyla
    297    Konul
    298    Nigar
    299     Ziya
    Name: customer, dtype: str
  4. 4.Print how many orders each city has.
    Show a hint
    value_counts() on the column city counts how often every city appears.
    Show one possible solution
    Python, continues from the cells above
    print(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.

  1. 5.Read a number n. Print the product and the price of the order at the position n, on one line.Examples: 42 gives Pillow 17.60 gives Mug 8.5299 gives Textbook 39.9
    Show 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 above
    n = int(input())
    row = df.iloc[n]
    print(row["product"], row["price"])

    Output

    Pillow 17.6
  2. 6.Print the rows at the positions 50 to 54 with the columns date, product and units.
    Show a hint
    With loc the columns go in by name and the slice includes its end: df.loc[50:54, [...]]. With iloc the slice is 50:55, and the columns are chosen afterwards.
    Show one possible solution
    Python, continues from the cells above
    print(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
  3. 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 print top["product"].tolist() and top["price"].tolist().
    Show one possible solution
    Python, continues from the cells above
    top = df.nlargest(3, "price")
    print(top["product"].tolist())
    print(top["price"].tolist())

    Output

    ['Smartwatch', 'Smartwatch', 'Smartwatch']
    [249.0, 249.0, 249.0]
  4. 8.Read the name of a category. Print how many orders this category has.Examples: Books gives 74Tech gives 68Home gives 56
    Show 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 above
    category = input()
    counts = df["category"].value_counts()
    print(counts[category])

    Output

    74
  5. 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 above
    df["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.

  1. 10.Sort the orders by units, the largest first, and orders with the same number of units by price, the largest first. Print the first 4 rows with the columns product, units and price.
    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 above
    ordered = 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
  2. 11.Make the customer names the row labels with set_index and store the result in by_customer. Print the columns date, product and price of all orders of the customer Sona.
    Show a hint
    by_customer = df.set_index("customer"). Then by_customer.loc["Sona", [...]] gives every row with this label.
    Show one possible solution
    Python, continues from the cells above
    by_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
  3. 12.This problem continues from Problem 9: the table already has the column total from your answer there. Save the columns date, product and total into the file totals.csv without the row labels. Read the new file and print its shape and its first 3 rows.
    Show a hint
    Choose the three columns with double brackets, then .to_csv("totals.csv", index=False). Read the file with pd.read_csv into a new variable. If Python says there is no column total, finish Problem 9 first.
    Show one possible solution
    Python, continues from the cells above
    df[["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
  4. 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 above
    shares = 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
  5. 14.Write a function top_products(df, n) that returns the n most often ordered products as a list.Examples: 3 gives ['Dictionary', 'Cookbook', 'Keyboard']1 gives ['Dictionary']4 gives ['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 above
    def 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']
  6. 15.Work on a copy of the table, shop, so that df stays as it is. In the copy, rename units to quantity, remove the column rating, and add a column price_usd: the price divided by 1.7, rounded to 2 decimals. Print the columns product, price, quantity and price_usd of the first 3 rows.
    Show a hint
    rename(columns={...}) and drop(columns=[...]) give new tables: store them back in shop. The new column: shop["price_usd"] = (shop["price"] / 1.7).round(2).
    Show one possible solution
    Python, continues from the cells above
    shop = 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.

Question 1

1.What does this print?

s = pd.Series([10, 20, 30], index=["a", "b", "c"])
print(s["b"], s.iloc[0])

Question 2

2.What does this print?

s = pd.Series([10, 20, 30, 40], index=["a", "b", "c", "d"])
print(len(s.loc["b":"c"]), len(s.iloc[1:2]))

Question 3

3.What does this print?

df = pd.DataFrame({"name": ["Aylin", "Murad", "Leyla"], "age": [20, 25, 22]})
print(df.shape)

Question 4

4.df is a DataFrame with the columns name and age. What does df["age"] give?

Question 5

5.Which line gives a table with the two columns name and age?

Question 6

6.Which call shows, for every column, how many values are not missing and which type it has?

Question 7

7.The row labels of df are 0, 1, 2 and so on. How many rows do df.loc[2:5] and df.iloc[2:5] give?

Question 8

8.What does this print?

df = pd.DataFrame({"x": [30, 10, 20]})
d = df.sort_values("x")
print(d.iloc[0]["x"], d.loc[0, "x"])

Question 9

9.What does this print?

df = pd.DataFrame({"x": [3, 1, 2]})
df.sort_values("x")
print(df["x"].tolist())

Question 10

10.What does this print?

s = pd.Series(["a", "b", "a", "c", "a"])
print(s.value_counts().iloc[0], s.nunique())

Question 11

11.What does this print?

df = pd.DataFrame({"price": [10, 20], "units": [3, 1]})
df["total"] = df["price"] * df["units"]
print(df["total"].tolist())

Question 12

12.You save a table with df.to_csv("out.csv") and read the file again with pd.read_csv("out.csv"). What is different?

0 of 12 answered.

14Quick summary

Quick summary
ConceptWhat it doesExample
import pandas as pdloads pandaspd.read_csv("orders.csv")
Seriesone column of values with labelspd.Series([85, 92], index=["Aylin", "Murad"])
DataFramea table of columnspd.DataFrame({"name": [...], "age": [...]})
read_csv / to_csvreads / saves a CSV filedf.to_csv("new.csv", index=False)
head / tailthe first / last rowsdf.head(3)
shape / dtypessize / type of every columndf.shape
info / describea summary / statisticsdf.info()
One columna Seriesdf["price"]
Several columnsa DataFramedf[["product", "price"]]
unique / nunique / value_countsdifferent values / how many / how oftendf["city"].value_counts()
ilocrows and columns by positiondf.iloc[0:3, 0:2]
locrows and columns by labeldf.loc[0:2, ["date", "price"]]
set_index / reset_indexa column as row labels / backdf.set_index("customer")
sort_valuessorts by a columndf.sort_values("price", ascending=False)
nlargest / nsmallestthe top / bottom rowsdf.nlargest(3, "price")
New columna calculation with whole columnsdf["total"] = df["price"] * df["units"]
rename / droprenames / removes columnsdf.drop(columns=["rating"])