Zero Grad›كورس Data Analysis›أساسيات Pandas›النوت بوك
← الدرسOpen in Kaggle

🐼 Pandas Basics: read, look, select, filter¶

Zero Grad · Data Analysis course · Pandas

📖 The lesson (in Arabic), with diagrams and interactive widgets: zero-grad.com/courses/da/pandas

🗂️ The data: NileCart Sales on Kaggle

This is the solved notebook of the Pandas basics lesson. NumPy gave us arrays of one type. Pandas puts many of them side by side, gives every column a name and every row a label: a table. Most of a data analyst's day is spent in it.

# Part The question
1 Series and DataFrame What is a table in Pandas?
2 Reading and writing How does a CSV become a table?
3 A first look What's in this table?
4 Columns Pick, add, rename, convert, drop
5 loc and iloc Rows by label, or by position?
6 Filtering Which rows match a condition?
7 Sorting What's on top?

0️⃣ Setup¶

In [1]:
from pathlib import Path

import numpy as np
import pandas as pd

pd.options.display.float_format = "{:,.2f}".format
pd.options.display.max_columns = 20

# On Kaggle the data lives under /kaggle/input, locally in the repo's data/nilecart/ folder
on_kaggle = sorted(Path("/kaggle/input").glob("**/sales.csv"))
DATA = on_kaggle[0].parent if on_kaggle else Path("../data/nilecart")
print(pd.__version__)
2.2.3

1️⃣ Series and DataFrame¶

A Series is one column: a NumPy array of values, plus an index (a label for every value).

In [2]:
price = pd.Series([1200, 450, 900], index=["Keyboard", "Mouse", "Backpack"], name="list_price")
price
Out[2]:
Keyboard    1200
Mouse        450
Backpack     900
Name: list_price, dtype: int64
In [3]:
print(price["Mouse"])          # by label
print(price.to_numpy())        # the NumPy array underneath
print(price * 1.14)            # vectorised, like NumPy, and the labels come along
450
[1200  450  900]
Keyboard   1,368.00
Mouse        513.00
Backpack   1,026.00
Name: list_price, dtype: float64

A DataFrame is a table: several Series that share the same index, one per column.

In [4]:
df = pd.DataFrame({
    "product": ["Keyboard", "Mouse", "Backpack"],
    "list_price": [1200, 450, 900],
    "category": ["Accessories"] * 3,
})
df
Out[4]:
product list_price category
0 Keyboard 1200 Accessories
1 Mouse 450 Accessories
2 Backpack 900 Accessories
In [5]:
print("index:  ", df.index)
print("columns:", df.columns.tolist())
print("one column is a Series:", type(df["list_price"]).__name__)
index:   RangeIndex(start=0, stop=3, step=1)
columns: ['product', 'list_price', 'category']
one column is a Series: Series
Part What it is df.
index the row labels (by default 0, 1, 2, …) index
columns the column names columns
values the data, one NumPy array per column to_numpy()
a column a Series df["col"]

2️⃣ Reading and writing¶

2.1 read_csv¶

In [6]:
sales = pd.read_csv(DATA / "sales.csv")
print(sales.shape)
print(sales["order_date"].dtype)      # text! a CSV has no types, Pandas guesses
(1466, 18)
object

A CSV file is only text. Pandas guesses each column's type: numbers become numbers, everything else stays text (object), dates included. Tell it which columns are dates:

In [7]:
sales = pd.read_csv(DATA / "sales.csv", parse_dates=["order_date"])
print(sales["order_date"].dtype)
print(sales["order_date"].min(), "->", sales["order_date"].max())
datetime64[ns]
2024-01-01 00:00:00 -> 2025-12-31 00:00:00

A few read_csv arguments you'll use often:

In [8]:
small = pd.read_csv(DATA / "sales.csv", usecols=["order_id", "product_name", "revenue"], nrows=5)
small
Out[8]:
order_id product_name revenue
0 10002 Notebook 315.00
1 10001 Laptop 259,920.00
2 10004 Notebook 570.00
3 10003 Notebook 285.00
4 10005 Keyboard 4,560.00
Argument Does
parse_dates=["col"] read these columns as dates
usecols=[...] read only these columns
nrows=5 read only the first rows (peek at a huge file)
index_col="col" use a column as the index
sep=";" another separator (many European files use ;)
encoding="utf-8" the text encoding (Arabic text needs the right one)

2.2 to_csv¶

In [9]:
big = sales[sales["revenue"] > 100_000]
big.to_csv("big_orders.csv", index=False)       # index=False: don't write 0, 1, 2 ... as a column
print(pd.read_csv("big_orders.csv").shape)
Path("big_orders.csv").unlink()                   # tidy up
(61, 18)

Forget index=False and the next read gets an extra column called Unnamed: 0.


3️⃣ A first look¶

Before any analysis, the same handful of questions, every time.

3.1 How big, and what does a row look like?¶

In [10]:
print(sales.shape)        # (rows, columns)
sales.head()              # the first 5 rows; tail() for the last, sample(5) for random ones
(1466, 18)
Out[10]:
order_id order_date customer_id name governorate region segment product_id product_name category quantity unit_price discount gross revenue unit_cost profit status
0 10002 2024-01-01 176 Fatma Hassan Cairo Greater Cairo Consumer 111 Notebook Stationery 5.00 63.00 0.00 315.00 315.00 20 215.00 cancelled
1 10001 2024-01-01 132 Yasmin Mostafa Cairo Greater Cairo Corporate 101 Laptop Electronics 9.00 30,400.00 0.05 273,600.00 259,920.00 27200 15,120.00 completed
2 10004 2024-01-02 131 Yasmin Fawzy Sharqia Delta Corporate 111 Notebook Stationery 10.00 57.00 0.00 570.00 570.00 20 370.00 completed
3 10003 2024-01-02 5 Mahmoud Abdelrahman Cairo Greater Cairo Small Business 111 Notebook Stationery 5.00 60.00 0.05 300.00 285.00 20 185.00 shipped
4 10005 2024-01-02 13 Tarek Saleh Cairo Greater Cairo Consumer 105 Keyboard Accessories 4.00 1,140.00 0.00 4,560.00 4,560.00 600 2,160.00 completed

3.2 What type is each column, and is anything missing? info()¶

In [11]:
sales.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1466 entries, 0 to 1465
Data columns (total 18 columns):
 #   Column        Non-Null Count  Dtype         
---  ------        --------------  -----         
 0   order_id      1466 non-null   int64         
 1   order_date    1466 non-null   datetime64[ns]
 2   customer_id   1466 non-null   int64         
 3   name          1466 non-null   object        
 4   governorate   1466 non-null   object        
 5   region        1466 non-null   object        
 6   segment       1466 non-null   object        
 7   product_id    1466 non-null   int64         
 8   product_name  1466 non-null   object        
 9   category      1466 non-null   object        
 10  quantity      1466 non-null   float64       
 11  unit_price    1466 non-null   float64       
 12  discount      1466 non-null   float64       
 13  gross         1466 non-null   float64       
 14  revenue       1466 non-null   float64       
 15  unit_cost     1466 non-null   int64         
 16  profit        1466 non-null   float64       
 17  status        1466 non-null   object        
dtypes: datetime64[ns](1), float64(6), int64(4), object(7)
memory usage: 206.3+ KB

info() answers three questions in one go: how many rows (1,466), each column's type, and how many values are non-null. 1,466 everywhere: sales.csv has no missing values. Its raw source does:

In [12]:
orders = pd.read_csv(DATA / "orders.csv")
orders.isna().sum()
Out[12]:
order_id        0
order_date      0
customer_id     0
product_id      0
quantity       30
unit_price      0
discount       40
status         10
dtype: int64

isna().sum() counts the missing values per column. The cleaning lesson deals with them.

3.3 Numbers: describe()¶

In [13]:
sales.describe().T
Out[13]:
count mean min 25% 50% 75% max std
order_id 1,466.00 10,754.06 10,001.00 10,382.25 10,756.50 11,125.75 11,500.00 431.91
order_date 1466 2025-02-11 16:54:40.763983616 2024-01-01 00:00:00 2024-08-26 00:00:00 2025-01-25 12:00:00 2025-09-02 00:00:00 2025-12-31 00:00:00 NaN
customer_id 1,466.00 89.79 1.00 50.00 85.00 131.75 902.00 59.23
product_id 1,466.00 106.39 101.00 104.00 106.00 109.00 111.00 2.98
quantity 1,466.00 4.09 1.00 2.00 4.00 5.00 10.00 2.38
unit_price 1,466.00 4,906.45 57.00 450.00 1,140.00 6,825.00 33,600.00 7,596.32
discount 1,466.00 0.05 0.00 0.00 0.00 0.10 0.20 0.07
gross 1,466.00 19,964.30 57.00 1,260.00 4,248.00 22,000.00 336,000.00 37,924.70
revenue 1,466.00 18,991.15 45.60 1,155.60 3,820.00 20,900.00 336,000.00 36,182.90
unit_cost 1,466.00 3,770.62 20.00 190.00 600.00 5,700.00 27,200.00 6,408.96
profit 1,466.00 3,679.80 -14,400.00 520.00 1,580.00 4,135.00 64,000.00 5,880.30

(The Descriptive statistics lesson is about reading this table.)

3.4 Categories: nunique() and value_counts()¶

In [14]:
sales.nunique()
Out[14]:
order_id        1466
order_date       605
customer_id      160
name             113
governorate       16
region             6
segment            4
product_id        11
product_name      11
category           4
quantity          10
unit_price        33
discount           4
gross            281
revenue          551
unit_cost         11
profit           562
status             5
dtype: int64
In [15]:
sales["status"].value_counts()
Out[15]:
status
completed    1074
shipped       195
returned      101
cancelled      86
unknown        10
Name: count, dtype: int64
In [16]:
sales["status"].value_counts(normalize=True).round(3)       # shares instead of counts
Out[16]:
status
completed   0.73
shipped     0.13
returned    0.07
cancelled   0.06
unknown     0.01
Name: proportion, dtype: float64

Things worth noticing already:

  • Only 73% of order lines are completed: revenue analysis should use those.
  • status has an unknown value, and region and segment have Unknown (2 rows each): dirty data to remember.
  • 1,466 order lines but only 160 customers: about 9 lines each.

4️⃣ Columns¶

4.1 Selecting¶

In [17]:
print(type(sales["revenue"]).__name__)                 # one name -> a Series
sales[["name", "product_name", "revenue"]].head(3)     # a list of names -> a DataFrame
Series
Out[17]:
name product_name revenue
0 Fatma Hassan Notebook 315.00
1 Yasmin Mostafa Laptop 259,920.00
2 Yasmin Fawzy Notebook 570.00

Note the double brackets: the outer ones select, the inner ones make a list.

4.2 New columns¶

Arithmetic on columns works element by element, like NumPy:

In [18]:
sales["margin"] = sales["profit"] / sales["revenue"]
sales["year"] = sales["order_date"].dt.year
sales["month"] = sales["order_date"].dt.month
sales[["order_date", "year", "month", "revenue", "profit", "margin"]].head(3)
Out[18]:
order_date year month revenue profit margin
0 2024-01-01 2024 1 315.00 215.00 0.68
1 2024-01-01 2024 1 259,920.00 15,120.00 0.06
2 2024-01-02 2024 1 570.00 370.00 0.65

.dt gives date parts (year, month, day_name(), …), .str gives text tools. Both work on the whole column:

In [19]:
sales["first_name"] = sales["name"].str.split().str[0]
sales[["name", "first_name"]].head(3)
Out[19]:
name first_name
0 Fatma Hassan Fatma
1 Yasmin Mostafa Yasmin
2 Yasmin Fawzy Yasmin

4.3 Renaming, converting, dropping¶

In [20]:
tidy = (sales
        .rename(columns={"product_name": "product"})
        .astype({"quantity": "int64"})              # sales.csv has no NaN, so this is safe
        .drop(columns=["first_name"]))
print(tidy.columns.tolist())
print(tidy["quantity"].dtype)
['order_id', 'order_date', 'customer_id', 'name', 'governorate', 'region', 'segment', 'product_id', 'product', 'category', 'quantity', 'unit_price', 'discount', 'gross', 'revenue', 'unit_cost', 'profit', 'status', 'margin', 'year', 'month']
int64

None of these change sales itself: they return a new DataFrame. Assign the result (tidy = ...) to keep it.


5️⃣ loc and iloc: rows by label, or by position¶

  • iloc[...] uses positions: 0, 1, 2, … like a list.
  • loc[...] uses labels: whatever is in the index.

With the default index (0, 1, 2, …) they look the same. Make order_id the index and the difference shows:

In [21]:
s = sales.set_index("order_id")
s[["name", "product_name", "revenue", "status"]].head(4)
Out[21]:
name product_name revenue status
order_id
10002 Fatma Hassan Notebook 315.00 cancelled
10001 Yasmin Mostafa Laptop 259,920.00 completed
10004 Yasmin Fawzy Notebook 570.00 completed
10003 Mahmoud Abdelrahman Notebook 285.00 shipped

The file isn't sorted by order_id: the first row is order 10002, the second is 10001.

In [22]:
print("iloc[0]     ->", s.iloc[0]["name"], "  (position 0: order", s.index[0], ")")
print("loc[10001]  ->", s.loc[10001, "name"], "  (label 10001)")
iloc[0]     -> Fatma Hassan   (position 0: order 10002 )
loc[10001]  -> Yasmin Mostafa   (label 10001)

5.1 Rows and columns together: [rows, columns]¶

In [23]:
s.loc[10001, ["product_name", "quantity", "revenue"]]
Out[23]:
product_name       Laptop
quantity             9.00
revenue        259,920.00
Name: 10001, dtype: object
In [24]:
s.iloc[:3, :4]          # the first 3 rows, the first 4 columns
Out[24]:
order_date customer_id name governorate
order_id
10002 2024-01-01 176 Fatma Hassan Cairo
10001 2024-01-01 132 Yasmin Mostafa Cairo
10004 2024-01-02 131 Yasmin Fawzy Sharqia

5.2 ⚠️ Slices: loc includes the end, iloc doesn't¶

In [25]:
print(len(s.iloc[0:3]), "rows with iloc[0:3]   (positions 0, 1, 2)")
print(len(s.loc[10002:10003]), "rows with loc[10002:10003]  (from label 10002 to label 10003, both included)")
s.loc[10002:10003, ["name", "product_name"]]
3 rows with iloc[0:3]   (positions 0, 1, 2)
4 rows with loc[10002:10003]  (from label 10002 to label 10003, both included)
Out[25]:
name product_name
order_id
10002 Fatma Hassan Notebook
10001 Yasmin Mostafa Laptop
10004 Yasmin Fawzy Notebook
10003 Mahmoud Abdelrahman Notebook

iloc slices like Python: the end is left out. loc slices by label, and includes both ends. A loc slice also follows the order the rows are in, not the order of the numbers: 10002, 10001, 10004, 10003 are the rows between those two labels.

5.3 Changing values: always through loc¶

In [26]:
fix = sales.copy()
fix.loc[fix["region"] == "Unknown", "region"] = "Not given"
fix["region"].value_counts().tail(2)
Out[26]:
region
Canal        63
Not given     2
Name: count, dtype: int64

df.loc[rows, column] = value is the one safe way to change part of a table. The chained form df[cond]["col"] = value changes a temporary copy, not df. In Pandas 2 it sometimes worked and raised a SettingWithCopyWarning; from Pandas 3 on it never changes df, and Pandas warns with a ChainedAssignmentError.


6️⃣ Filtering¶

The NumPy boolean mask, with column names:

In [27]:
mask = sales["status"] == "completed"
print(mask.head(4).tolist())
done = sales[mask]
print(len(done), "of", len(sales), "rows")
[False, True, True, False]
1074 of 1466 rows

6.1 Several conditions: &, |, ~, in brackets¶

In [28]:
print("completed Electronics: ", len(sales[(sales["status"] == "completed") & (sales["category"] == "Electronics")]))
print("returned or cancelled: ", len(sales[(sales["status"] == "returned") | (sales["status"] == "cancelled")]))
print("not completed:         ", len(sales[~mask]))
completed Electronics:  269
returned or cancelled:  187
not completed:          392

6.2 Shortcuts: isin, between, .str.contains¶

In [29]:
print("isin:     ", len(sales[sales["status"].isin(["returned", "cancelled"])]))
print("between:  ", len(done[done["revenue"].between(1_000, 5_000)]), "completed lines between 1,000 and 5,000 EGP (both ends included)")
print("contains: ", len(sales[sales["name"].str.contains("Mostafa")]), "lines for customers with Mostafa in the name")
isin:      187
between:   357 completed lines between 1,000 and 5,000 EGP (both ends included)
contains:  222 lines for customers with Mostafa in the name

6.3 query: the condition as a string¶

In [30]:
sales.query("status == 'completed' and revenue > 100_000")[["order_id", "name", "product_name", "revenue"]].head()
Out[30]:
order_id name product_name revenue
1 10001 Yasmin Mostafa Laptop 259,920.00
66 10070 Laila Fawzy Phone 144,000.00
106 10112 Amr Farouk Phone 153,900.00
182 10190 Amr El-Sayed Laptop 168,000.00
250 10262 Dina Hassan Laptop 159,600.00
In [31]:
cutoff = 100_000
len(sales.query("status == 'completed' and revenue > @cutoff"))      # @ uses a Python variable
Out[31]:
43

query reads well for long conditions; brackets work everywhere. Use whichever is clearer.

6.4 Filter, then pick columns, in one loc¶

In [32]:
sales.loc[(sales["status"] == "completed") & (sales["region"] == "Canal"), ["order_date", "name", "product_name", "revenue"]].head()
Out[32]:
order_date name product_name revenue
12 2024-01-14 Reem Fawzy Monitor 66,150.00
20 2024-01-21 Reem Fawzy Lamp 5,250.00
165 2024-05-05 Nour Abdelrahman Notebook 240.00
172 2024-05-11 Dina Fawzy Phone 56,700.00
178 2024-05-13 Reem Fawzy Desk 26,000.00

7️⃣ Sorting¶

In [33]:
done.sort_values("revenue", ascending=False)[["order_id", "name", "product_name", "revenue"]].head()
Out[33]:
order_id name product_name revenue
664 10683 Yasmin Saleh Laptop 336,000.00
837 10861 Reem Fawzy Laptop 320,000.00
1 10001 Yasmin Mostafa Laptop 259,920.00
600 10616 Amr Ibrahim Laptop 230,400.00
1307 11343 Dina Hassan Laptop 215,040.00

The three biggest order lines are all laptops, the same answer argsort gave in the NumPy lesson. sort_values is that argsort, applied to every column at once so the rows stay whole.

Sort by several columns: the second breaks ties in the first.

In [34]:
(done.sort_values(["category", "revenue"], ascending=[True, False])
     .groupby("category").head(1)[["category", "product_name", "revenue"]])
Out[34]:
category product_name revenue
1104 Accessories Keyboard 12,600.00
664 Electronics Laptop 336,000.00
321 Furniture Desk 55,575.00
748 Stationery Notebook 630.00
In [35]:
done.nlargest(3, "profit")[["name", "product_name", "profit"]]          # shortcut for sort + head
Out[35]:
name product_name profit
664 Yasmin Saleh Laptop 64,000.00
837 Reem Fawzy Laptop 48,000.00
182 Amr El-Sayed Laptop 32,000.00
In [36]:
s.sort_index().head(3)[["name", "product_name"]]                        # sort by the index labels
Out[36]:
name product_name
order_id
10001 Yasmin Mostafa Laptop
10002 Fatma Hassan Notebook
10003 Mahmoud Abdelrahman Notebook

🧰 Summary¶

Task Code
Read a CSV, with dates pd.read_csv(path, parse_dates=["order_date"])
Write a CSV df.to_csv(path, index=False)
Size, first rows df.shape, df.head(), df.sample(5)
Types and missing df.info(), df.isna().sum()
Numbers, categories df.describe(), df.nunique(), df["col"].value_counts()
One column / several df["col"] (Series) / df[["a", "b"]] (DataFrame)
New column df["margin"] = df["profit"] / df["revenue"], .dt.year, .str.split()
Rename, convert, drop rename(columns=...), astype(...), drop(columns=...)
By position / by label df.iloc[0:3, :4] (end excluded) / df.loc[10001, "name"] (end included)
Change values df.loc[cond, "col"] = value
Filter df[(cond1) & (cond2)], isin, between, .str.contains, query
Sort sort_values(cols, ascending=...), nlargest, sort_index

Next lesson: grouping and joining: groupby, pivot_table and merge.

📚 All the lessons of the course: zero-grad.com/courses/da