Python Tutorial
Pandas Introduction
Pandas is the main library for tabular data in Python. Series is one column. DataFrame is a table. It sits on top of NumPy.
What Is Pandas?
Use Pandas to load CSV/JSON, clean missing values, filter rows, group, merge, and plot. It is the usual first stop after NumPy in a data-science workflow.
Chapters in This Section
| Chapter | You will learn |
|---|---|
| Getting Started | Install and import |
| Series | One-dimensional labeled array |
| DataFrames | Tables with rows and columns |
| Read CSV | read_csv |
| Read JSON | read_json |
| Analyzing | head, info, describe |
| Selecting | loc and iloc |
| Cleaning | Missing values and duplicates |
| GroupBy | Split-apply-combine |
| Merge | Join DataFrames |
| Plotting | Quick charts from a DataFrame |
Series and DataFrame
A Series is a labelled 1-D column; a DataFrame is a 2-D table of Series sharing an index — think of a spreadsheet in Python.
import pandas as pd
df = pd.DataFrame({
"name": ["Ann", "Bob", "Cara"],
"age": [30, 25, 35],
"city": ["NYC", "LA", "NYC"],
})
print(df.head()) # first rows
print(df["age"].mean()) # 30.0
print(df.shape) # (3, 3)Filtering, Selecting, Grouping
# boolean filtering
print(df[df["age"] > 28])
# select by label / position
print(df.loc[0, "name"]) # Ann
print(df.iloc[0, 0]) # Ann
# group and aggregate
print(df.groupby("city")["age"].mean())
# city
# LA 25.0
# NYC 32.5Use .loc[] for label-based access and .iloc[] for position-based access — mixing them up is a common beginner error.
Try It Yourself
Exercise 1: From the DataFrame above, print the names of everyone in NYC.
Show solution
print(df[df["city"] == "NYC"]["name"].tolist()) # ['Ann', 'Cara']Exercise 2: Add a column senior that is True when age > 30.
Show solution
df["senior"] = df["age"] > 30
print(df)Key Takeaways
- DataFrames are labelled 2-D tables; Series are single columns.
- Filter with boolean masks; select with
.loc/.iloc. groupby+ an aggregation summarizes data fast.- Read/write CSV, Excel, JSON, and SQL with one call each.
📘 Real-World Deep Dive
pandas wraps NumPy arrays with named columns and date indexes, and adds groups, joins, missing-data handling, and rich I/O. Once you think in DataFrames, almost any tabular task becomes legible.
Real-Life Scenario
Realistic sales pipeline: load a 100 k-row CSV, normalise dates, audit per-customer revenue in a weekly time window, and emit the result back as Parquet.
Real-Life Example
import pandas as pd
# In real life: df = pd.read_csv("orders.csv", parse_dates=["created_at"])
df = pd.DataFrame({
"customer": ["ada", "bo", "cy", "de"] * 250,
"created_at": pd.date_range("2026-01-01", periods=1000, freq="h"),
"amount": [10, 20, 5, 30] * 250,
})
df = df.assign(amount=df["amount"].astype("float32"))
# Resample per customer × week
grouped = (
df.set_index("created_at")
.groupby("customer")
.resample("W")
.agg(revenue=("amount", "sum"), orders=("amount", "count"))
.reset_index()
)
print(grouped.head())
print("
week with peak revenue per customer:")
peak = grouped.loc[grouped.groupby("customer")["revenue"].idxmax()]
print(peak)
# Out as Parquet — small, typed, columnar
# grouped.to_parquet("weekly.parquet")Expected Output
customer created_at revenue orders
0 ada 2026-01-05 60.0 2
1 ada 2026-01-12 60.0 2
...
week with peak revenue per customer:
customer created_at revenue orders
ada 2026-04-27 720.0 12
bo 2026-05-04 600.0 10
...Common mistakes
df[df.col > x]returns a copy and triggers aSettingWithCopyWarningon writes; assign viadf.loc[mask, col].- Pandas treats a regular list-of-dicts as
objectdtype; cast withpd.to_numeric/astype("category")for big speedups. df.iterrows()is O(n) and slow; useitertuples()ordf.eval/df.queryfor batched work.
🚀 Performance & Best Practices
- Switch the IO engine:
pd.read_csv(..., engine="pyarrow", dtype_backend="pyarrow")is much faster. .astype("category")collapses repeated text into a small dictionary — sort and group-by speed up dramatically.- For datasets > 1 GB, work with
modin/polarsinstead of eager pandas.
🧪 Try It Yourself
- Add a per-customer moving-7-day revenue column.
- Compute week-over-week growth and flag negative weeks.
- Read the source as Parquet +
pyarrowand compare with CSV performance.