…
…
Statistics and Data Analysis Fundamentals · Lesson 4 / 44 · DataFrames and selecting
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
In the first three lessons you read Bazaar's 885 orders with the csv module and loops, and every question took a few lines of code. Now the manager wants a short "what do we have?" report. In this lesson you will open the same table with pandas in one line, get to know it with a few commands, and write the report as three observations.
By the end of the lesson you will have written these three sentences about the orders table with your own code, finding the numbers yourself:
1. The table has 885 orders and 13 columns. Each row is one order (order_id never repeats), and there are 524 different customers.
2. Only delivery_days has empty cells. Delivery days are empty for 34 orders (they may be canceled orders; we will check in lesson 19).
3. Amounts range from $5.81 to $899.90, with an average of $75.5. The difference between the list price and the amount, which is the total discount, is $1,821.6.
In this lesson you will:
In lesson 2 you read the table like this: open the file, turn the rows into a list of dictionaries with csv.DictReader, then use len for the number of rows and set for the different customers. The code worked, but every new question needed a new loop or list comprehension.
import csv with open("orders.csv", encoding="utf-8") as f: rows = list(csv.DictReader(f)) print(len(rows), len(set(r["customer_id"] for r in rows)))
Output885 524pandas is the standard Python library for working with tables. Almost every data analyst uses it to open, clean, and summarize tables. You import it with the import ... as pattern you saw in the Python course, and by convention it is shortened to pd. The same job looks like this with pandas:
import pandas as pd df = pd.read_csv("orders.csv") print(df.shape, df["customer_id"].nunique())
Output(885, 13) 524The numbers are the same: 885 orders and 524 different customers. pandas also gave you one more fact: the table has 13 columns. It opened the file, split the rows, and read the column names for you. In the rest of this lesson we will open up what happens inside these two lines.
pd.read_csv("orders.csv") reads the file and returns a DataFrame. A DataFrame is a table with rows and columns. By habit, we name it df. While reading, pandas does three things: it takes the first row as the column names, it guesses the type of each column by looking at the values, and it gives each row a number starting from 0. This number is called the index. You see it on the far left when you print the table.
To take one column from the table, you write the column name in square brackets: df["amount"]. The result is a Series, which is a single column with a name. In lesson 2 we said "every column is a variable"; a Series is all the values of that variable. If you want several columns at once, you put a list of column names inside the square brackets: df[["order_id", "amount"]]. The outer brackets mean "select" and the inner brackets mean "list". The result is again a DataFrame, only narrower. This is very useful for fitting a wide table on the screen.
Example 1 (case): First rows and size
import pandas as pd df = pd.read_csv("orders.csv") print(df.shape) print(df[["order_id", "date", "device", "category", "amount"]].head()) print(type(df["amount"]).__name__, type(df[["amount"]]).__name__)
Output(885, 13)
order_id date device category amount
0 S00001 2026-01-01 desktop Home & Living 249.90
1 S00002 2026-01-02 desktop Electronics 74.95
2 S00003 2026-01-02 desktop Home & Living 164.95
3 S00004 2026-01-02 mobile Books 15.95
4 S00005 2026-01-02 mobile Home & Living 44.95
Series DataFrameLook at the last line: df["amount"] is a Series, and df[["amount"]] is a DataFrame with one column. They look similar on the screen, but they are not the same thing. If you take the average of the Series, you get a single number. If you take the average of the one-column DataFrame, you get a small table with the column name. When you want a single number, such as the average, total, or count of one column, you use the single-bracket form.
The first-look code is always written in the same order. Put the lines in the right order.
Put the lines of the code that first looks at a data file in the right order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
When you open a dataset, you always start with the same questions. How many rows and columns are there? What type was each column read as? Are there empty cells? You want to know the answers before you start the analysis, because every later step depends on them.
df.shape returns a tuple: (885, 13) means 885 rows and 13 columns. The column names are in df.columns. The type of each column is shown by df.dtypes. These three are attributes: ready-made facts about the table, written without parentheses. head(), on the other hand, is a method: it does a job, so it is called with parentheses. You choose how many rows to see by writing a number inside the parentheses; head(3) gives the first 3 rows, and if you leave it empty you get 5 rows. The same difference applies here as in the string methods (.upper()) and lists (len(items)) you saw in the Python course.
What happens when you write df.shape()?
In the df.dtypes output you will see three types. int64 is an integer, float64 is a float, and str is a string. Since pandas 3.0, text columns are read as type str. The date column is also a string for now: pandas saw it as the text "2026-01-01". To calculate with dates, you will need to convert it; we will do this in lesson 6.
import pandas as pd df = pd.read_csv("orders.csv") print(df.dtypes)
Outputorder_id str
date str
customer_id str
device str
product_id str
category str
quantity int64
unit_price float64
discount float64
amount float64
status str
carrier str
delivery_days float64
dtype: objectEmpty cells appear in pandas as NaN ("not a number"). df.isna().sum() tells you how many empty cells each column has: isna() answers "is it empty?" with true or false for every cell, and sum() counts the trues in each column. It is the same idea as in lesson 2, where the sum of a 0/1 column gave the number of "yes" values.
import pandas as pd df = pd.read_csv("orders.csv") print(df.isna().sum())
Outputorder_id 0
date 0
customer_id 0
device 0
product_id 0
category 0
quantity 0
unit_price 0
discount 0
amount 0
status 0
carrier 0
delivery_days 34
dtype: int64Only the delivery_days column has empty cells: 34. This is the second sentence of your first observation. Look at one more detail: delivery days are whole numbers like 1, 2, 3, but the type is float64. The reason is the empty cells: a numeric column with empty values is read as float. When a column's type is different from what you expected, it is the first clue that something in it is different.
Now match each question with the tool that answers it.
Choose the right tool for each question.
For each row, pick its match from the list, then check.
When you select a single column, getting its summary is easy. A numeric Series has the methods mean(), sum(), min(), max(), and count(). count() counts the values that are not empty, while len counts all rows. describe() gives eight summaries of a column at once. In this lesson we will read only four of them: count (number of filled values), mean (average), min, and max. You will see what the others (std, 25%, 50%, 75%) mean in lessons 12–15; it is normal if you do not understand them yet.
Example 2 (case): Summary of one column
import pandas as pd df = pd.read_csv("orders.csv") print(df["amount"].describe().round(1))
Outputcount 885.0
mean 75.5
std 101.2
min 5.8
25% 22.4
50% 45.0
75% 84.0
max 899.9
Name: amount, dtype: float64The first half of the third observation comes from here: the amount is filled in all 885 orders, the smallest amount is about $5.8, the largest is $899.9, and the average is $75.5. round(1) rounds the numbers to one decimal place so the output is easy to read.
Empty cells do not break the summary. When pandas calculates summaries such as mean() and sum(), it skips the empty cells; it does not count them as zero. The average of delivery days is not the average of 885 orders, but of the 851 orders where delivery days are filled. If you want only the filled values as a separate Series, you use dropna(): df["delivery_days"].dropna() gives 851 values. Thinking "an empty value pulls the average down to zero" is a common mistake, but it is a good habit to say how many values an average is based on when you report it.
For categorical columns, the most used tool is value_counts(): it counts how many times each value appears and sorts from most to least. In lesson 2 you did the same job with Counter and most_common. nunique() gives the number of different values.
Example 3 (case): Categorical columns and a column with empty cells
import pandas as pd df = pd.read_csv("orders.csv") print(df["device"].value_counts()) print("Different customers:", df["customer_id"].nunique()) print(df["delivery_days"].count(), round(df["delivery_days"].mean(), 2))
Outputdevice
mobile 516
desktop 369
Name: count, dtype: int64
Different customers: 524
851 2.98The last line says two things: delivery days are filled in 851 orders (885 − 34), and the average delivery time of these 851 orders is 2.98 days. Try it yourself in the cell below and do the tasks in the comments one by one.
Try it now· not graded; doesn't affect progress
Analysis often asks for a number that is not ready in the table. Bazaar's table has quantity and unit_price; to find the list total of each order without any discount, you need to multiply the two. In lesson 2 you would build a loop, multiply in each row, and add the result to a list. In pandas you do it in one line: df["quantity"] * df["unit_price"]. pandas multiplies the quantity of the first row by the price of the first row, the second by the second, and so on, and gives the 885 results as a new Series. This is called a vectorized calculation.
There is a trap here. In Python lists, the same notation does something completely different. Predict first.
What does this code print?
import pandas as pd print([1, 2] * 2, (pd.Series([1, 2]) * 2).tolist())
Because the result is a new Series, you can also take its total or average. You can also use a column with a fixed number: df["amount"] / 1.20 removes a 20% tax from every amount (20% is an example rate in this lesson). For now we keep these new numbers in a variable; you will add them to the table as a new column in lesson 6.
Example 4 (case): List total and total discount
import pandas as pd df = pd.read_csv("orders.csv") list_total = df["quantity"] * df["unit_price"] print(list_total.head(3)) print(round(list_total.sum(), 1), round(df["amount"].sum(), 1)) print("Total discount:", round((list_total - df["amount"]).sum(), 1))
Output0 249.90
1 74.95
2 164.95
dtype: float64
68665.2 66843.6
Total discount: 1821.6At list prices, the orders would have come to $68,665.2; the customers paid $66,843.6 in total. The difference between them, the total discount given to customers, is $1,821.6. The second half of the third observation is ready too. list_total - df["amount"] is also a vectorized calculation: it finds the discount of each order, and then sum() adds them all.
See how one line is applied to all rows in a small example. Below are the prices and quantities of three orders; change the discount rate and watch the results.
Change the discount rate. How does the one-line calculation affect all three orders?
Pick a value; predict the output first, then look.
1import pandas as pd23rate = 04price = pd.Series([15.0, 9.0, 2.5])5quantity = pd.Series([2, 1, 4])6amount = price * quantity * (1 - rate)7print(amount.round(1).tolist())8print("Total:", round(amount.sum(), 1))
[30.0, 9.0, 10.0] Total: 49.0
Faded lines didn't run with this value. The line price * quantity * (1 - rate) was written once but applied to all three orders: each price was multiplied by the quantity next to it, and then all of them were reduced by the same rate. round(1) hides floating-point leftovers (like 27.000000000000004).
Vectorized calculation is not only for the orders table. Bazaar's products.csv file has the list price and the cost of each product. The difference between the two is the gross profit per product: what is left of the price after the cost is taken out when a product is sold.
Example 5 (case): Gross profit per product
import pandas as pd p = pd.read_csv("products.csv") print(p.shape) profit = p["list_price"] - p["cost"] print(profit.head(3).round(2).tolist(), round(profit.mean(), 1))
Output(40, 5)
[20.85, 50.45, 18.3] 20.4There are 40 products; the first product (wireless headphones) leaves $20.85 on every sale, and the average gross profit of the products is $20.4. Now it is your turn: divide the profit by the price to turn it into a percentage margin.
Try it now· not graded; doesn't affect progress
Not every table comes from a file. You can also build a small table from a dictionary: the keys become column names and the values become the lists of those columns. pd.DataFrame({...}) turns the dictionary into a table. This is very handy for trying an idea quickly.
Example 6 (outside the case): Grade average
In a course, the midterm counts for 40% and the final counts for 60%. Let's calculate the course grade of four students in one line.
import pandas as pd table = pd.DataFrame({ "name": ["Ada", "Bora", "Cem", "Deniz"], "midterm": [70, 55, 90, 40], "final": [80, 65, 85, 60], }) grade = table["midterm"] * 0.4 + table["final"] * 0.6 print(grade.tolist()) print(grade.mean())
Output[76.0, 61.0, 87.0, 52.0]
69.0The code stays the same whether there are 4 rows or 40,000. The class average is 69. Now try what you would do when you meet a new file, in a scenario.
A new data file arrived: campaign.csv. The manager says "tell me in five minutes what we have." You read the file as df. What is your first command?
Pick an option and see what happens. There are no points; you can try the other options too.
At the end of the first look, you have a lot of numbers. You give the manager observations, not a list of numbers. A good observation has three parts: the number, the unit, and what the number means. "885" is a number; "The table has 885 orders and 13 columns; each row is one order" is an observation. Also note empty values and unexpected types, but do not write something as certain when you are not sure about its cause. Saying "they may be canceled orders" for the 34 empty delivery days is correct; saying "there are 34 faulty records" is a judgment that does not come from the data.
You can now build the three observations from the start of the lesson yourself: size and different customers came from shape and nunique(), the empty cells from isna().sum(), the range and average of the amount from describe(), and the total discount from the vectorized calculation.
Dividing a column by a fixed number is also a vectorized calculation. Let's assume the amounts include 20% tax (an example rate).
import pandas as pd df = pd.read_csv("orders.csv") no_tax = df["amount"] / 1.20 print(no_tax.head(3).round(1).tolist()) print(round(no_tax.sum(), 1))
Output[208.2, 62.5, 137.5]
55703.0Each amount was divided by 1.20 separately; the total revenue without tax is $55,703.
The same first look tells a different story in another table. In sessions.csv, checkout time is measured only in sessions that reached the checkout page.
import pandas as pd s = pd.read_csv("sessions.csv") print(s.shape) print(s["checkout_time_sec"].isna().sum(), s["reached_checkout"].sum()) print(s["checkout_time_sec"].count(), round(s["checkout_time_sec"].mean(), 1))
(1000, 8) 805 195 195 116.3
Writing `df.shape()`. shape is an attribute; with parentheses you get the error "'tuple' object is not callable". The same is true for df.columns and df.dtypes. The opposite is also a mistake: if you write df["amount"].mean (without parentheses), you do not get a number, but the method itself, a description that starts with <bound method Series.mean ...>. The rule: if you are reading information, no parentheses (shape, columns, dtypes); if you are asking for a job to be done, with parentheses (head(), mean(), describe(), value_counts()).
pd.read_csv opens a CSV file as a DataFrame; df["column"] gives one column as a Series, and df[["a", "b"]] gives a list of columns as a DataFrame again.shape, dtypes (no parentheses), isna().sum(), head(), describe(), value_counts(), nunique(); summaries skip empty cells.df["quantity"] * df["unit_price"] is the list total without a loop.Next lesson: we got to know the whole table, but analysis questions ask for a part of it (only May, only mobile, the biggest orders), so we will learn selecting, filtering, and sorting.
Exercises and quiz are for members
This lesson has 6 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
Checkout time is empty in 805 of the 1,000 sessions, and the number of sessions that reached the checkout page is exactly 195. The empty cells here are not an error; they mean "there was nothing to measure." The average of 116.3 seconds is based on these 195 sessions.