The one-line mental model
A Series is a single labeled column; a DataFrame is a stack of Series that share an index â and almost every Pandas bug comes from confusing label-based access with position-based access, or from leaving a column as object when it should be numeric.
In this lesson you will be able to:
- Build Series and DataFrames from dicts, lists, NumPy arrays, and CSV files
- Choose between
loc,iloc, and bracket indexing without off-by-one surprises - Inspect structure with
info,describe,dtypes, andvalue_counts - Convert string columns to numeric and datetime types safely
- Detect, drop, and fill missing values with column-aware strategies
Prerequisites
- !Python lists, dicts, and comprehensions
- !NumPy array basics
- !What a CSV file is
What You'll Learn
- 1Explain the relationship between Series, DataFrame columns, and the index
- 2Use loc and iloc for row, column, and boolean selection
- 3Convert messy string columns with to_numeric and to_datetime
- 4Audit missing data and apply targeted fill or drop strategies
Why indexing surprises nearly everyone
Pandas looks like a spreadsheet until the first time a slice behaves differently than you expected. The root cause is that a DataFrame carries two coordinate systems at once: labels (index values and column names) and integer positions. loc speaks labels; iloc speaks positions. On a default RangeIndex the two coincide, so beginner code works â until someone sets index=["emp1", "emp2", ...], sorts the frame, or filters it, and suddenly iloc[0] is not the row you remember.
A second trap is dtype drift. When you read a CSV in which the price column contains a stray "N/A" token, Pandas stores the entire column as object (Python strings). Arithmetic then either raises or silently concatenates, and describe() skips the column entirely. The fix is never to eyeball dtypes â check df.dtypes after every load and convert deliberately with to_numeric(..., errors="coerce").
Finally, missing data hides in plain sight. None, NaN, and pd.NA all register under isna(), but a column can also contain the string "missing", which does not. A rigorous workflow starts with a missing-value audit before any imputation decision.
Building Series and DataFrames from scratch
A Series wraps one NumPy array with an index and a name. You can construct one from a list, a dict (keys become the index), or even a scalar that is broadcast.
import pandas as pd
import numpy as np
# Series from a list â default integer index
s = pd.Series([12.5, 18.0, 9.75, 22.4], name="daily_sales")
print(s.mean(), s.std(), s.describe())
# Series from a dict â keys become labels
prices = pd.Series({"apples": 1.50, "bananas": 0.75, "cherries": 3.25})
print(prices["bananas"]) # 0.75
print(prices > 1.0) # boolean Series you can filter with
# DataFrame from a dict of lists
df = pd.DataFrame({
"name": ["Alice", "Bob", "Charlie", "Diana"],
"age": [25, 30, 35, 28],
"city": ["NYC", "LA", "Chicago", "Houston"],
"salary": [70000, 80000, 90000, 75000],
}, index=["emp1", "emp2", "emp3", "emp4"])
print(df.shape) # (4, 4)
print(df.columns) # Index(['name', 'age', 'city', 'salary'], dtype='object')
print(df.dtypes) # name=object, age=int64, city=object, salary=int64
Vectorized operations are the reason Pandas beats loops. df["salary"] / 1000 touches every row in compiled C code; a Python for over iterrows() does not. Reach for apply only when a rule genuinely cannot be expressed as an element-wise or aggregation method.
loc, iloc, and boolean selection
Once the index is non-default, label and position diverge. The table below is the cheat sheet worth memorizing.
| Accessor | Coordinates | Slice behavior | Typical use |
|---|---|---|---|
df.loc[rows, cols] | Index labels and column names | Inclusive on both ends | Filter by business keys like "emp2" |
df.iloc[rows, cols] | Integer positions only | Exclusive end, like Python | Grab "the first three rows" |
df[bool_series] | Row mask | Keeps matching rows | Query-style filtering |
df[["col"]] | Column names | Returns a DataFrame | Keep 2-D shape for pipelines |
# Label-based access (inclusive end)
print(df.loc["emp1":"emp3", "name":"age"])
# Position-based access (exclusive end)
print(df.iloc[0:2, [0, 2]])
# Boolean filtering plus column projection
mask = (df["age"] >= 28) & (df["city"].isin(["NYC", "Chicago"]))
print(df.loc[mask, ["name", "salary"]])
# Chained assignment is a classic SettingWithCopyWarning source;
# do this instead:
df = df.assign(salary_k=df["salary"] / 1000)
The assign method returns a new DataFrame rather than mutating a slice in place, which keeps downstream code reproducible and silences the dreaded SettingWithCopyWarning.
Auditing structure with info and describe
Before modeling, you want a structural snapshot: how many rows, which types, how many non-null values per column, and roughly what the distributions look like. Two calls answer almost all of it.
survey = pd.DataFrame({
"age": [25, np.nan, 35, 28, 40],
"salary": [70000, 80000, np.nan, 75000, 95000],
"dept": ["eng", "eng", "sales", "eng", "sales"],
})
print(survey.info())
# RangeIndex: 5 entries, 0 to 4
# Non-Null Count Dtype
# age 4 non-null float64
# salary 4 non-null float64
# dept 5 non-null object
print(survey.describe()) # numeric summary only
print(survey.describe(include="all")) # adds top, freq for object cols
print(survey["dept"].value_counts(normalize=True))
value_counts(normalize=True) is especially useful for categorical columns â it turns raw counts into class proportions, which is the first thing you check when a classification target looks imbalanced.
Converting dtypes without silent corruption
Type conversion is where clean-looking data goes to die. A single "1,299.00" string among otherwise numeric prices will coerce to NaN under to_numeric and to a wrong value under a naive float(). The safe pattern is convert, then measure how much you lost.
messy = pd.DataFrame({
"price": ["19.99", "42.50", "1,299.00", "N/A"],
"quantity": ["3", "5", "two", "2"],
"date": ["2024-01-15", "2024-02-20", "2024-03-25", "2024-04-01"],
})
# Strip thousands separators, then coerce
messy["price"] = pd.to_numeric(
messy["price"].str.replace(",", "", regex=False), errors="coerce"
)
print(messy["price"].isna().sum()) # count how many rows you just nullified
messy["date"] = pd.to_datetime(messy["date"], format="%Y-%m-%d")
messy["month"] = messy["date"].dt.month
messy["day_of_week"] = messy["date"].dt.day_name()
print(messy.dtypes)
Always compare the null count before and after coercion. A jump from zero nulls to three means your parser is eating real data, and the pipeline downstream will quietly under-count revenue.
Missing data: audit first, then decide
Blanket dropna() or fillna(0) are red flags in review. The right move depends on why the value is missing and how much of the column is affected.
| Situation | Recommended strategy |
|---|---|
| Under 1% missing, MCAR | Drop the rows (dropna(subset=[...])) |
| Numeric, skewed distribution | Fill with median |
| Numeric with temporal order | Forward-fill or interpolate |
| Categorical, "not applicable" is meaningful | Fill with a dedicated "Unknown" label |
| Missingness itself is predictive | Add an is_missing flag column, then impute |
audit = survey.isna().sum().rename("nulls").to_frame()
audit["pct"] = (audit["nulls"] / len(survey) * 100).round(1)
print(audit.sort_values("pct", ascending=False))
filled = survey.copy()
filled["age"] = filled["age"].fillna(filled["age"].median())
filled["dept"] = filled["dept"].fillna("Unknown")
filled["salary_missing"] = filled["salary"].isna().astype(int)
filled["salary"] = filled["salary"].ffill()
print(filled)
Note the order of operations: create the missingness flag before filling, otherwise the signal is destroyed. That one flag often carries more predictive power than the imputed value itself in fraud or churn models.
Sorting, aggregating, and the groupby bridge
Sorting is not cosmetic â it is how you verify order-dependent logic, find boundary cases, and prepare data for window functions that rely on row position. sort_values with a list of columns and explicit ascending flags handles multi-key ordering; kind="stable" preserves relative order within ties, which matters when the tie order carries meaning (say, events within the same second). Always inspect the first few rows after sorting to confirm the order is what you intended before chaining further operations.
Groupby is the bridge from row-level data to segment-level insight. Split-apply-combine is the mental model: split the frame into groups by one or more keys, apply an aggregation or transformation to each group, and combine the results back into a new structure. The distinction between an aggregation (one row per group) and a transformation (same-shaped output, values broadcast back to their original rows) is the most common source of confusion. Getting this distinction right unlocks the majority of real-world pandas workflows.
Sorting is not just for display â groupby assumes a well-defined order when you compute rolling or cumulative statistics. nlargest and nsmallest are also faster and more readable than sort-then-slice.
sales = pd.DataFrame({
"region": ["East", "West", "East", "West", "East"],
"product": ["A", "A", "B", "B", "A"],
"amount": [120, 340, 90, 410, 260],
})
print(sales.sort_values(["region", "amount"], ascending=[True, False]))
print(sales.nlargest(2, "amount"))
summary = (
sales.groupby(["region", "product"])["amount"]
.agg(total="sum", mean="mean", n="count")
.reset_index()
)
print(summary)
The named-aggregation syntax (agg(total="sum", ...)) produces tidy column names directly, so the result feeds straight into a chart or a report without a rename pass.