Pandas for Data Analysis
Chapter 23's NumPy arrays are fast and vectorized, but they're strictly homogeneous — every element shares one dtype, and there's no built-in idea of a "column name." Real-world data is rarely that tidy: a sales record has a product name (text), a region (text), and a revenue figure (a number), all in the same row. pandas is built directly on top of NumPy specifically to handle this — labeled, heterogeneous-column tables, with the same underlying speed. It's the single most-used data-analysis library in Python, and it's what turns "a CSV file" into "an answer to a real question" in a handful of lines.
How to read this chapter
- Sub-topic 1 makes the case for pandas on top of what Chapter 23 already built — DataFrames and Series versus NumPy arrays, with a concrete motivating question over real data.
- Sub-topic 2 covers building a DataFrame two ways: from a dict of lists, and from a real CSV with
pd.read_csv()— including a direct, measured contrast against Chapter 13'scsvmodule. - Sub-topic 3 covers reading a DataFrame back out:
.head(),.info(),.describe(),.shape,.columns,.dtypes. - Sub-topic 4 covers selecting columns, boolean filtering, and the
.loc[]-vs-.iloc[]distinction — the single most common beginner trip-up in pandas. - Sub-topic 5 covers adding/modifying columns and a real first encounter with messy, missing data.
- Sub-topic 6 covers
.groupby(), aggregation, and sorting — the exact toolkit this chapter's sales-dashboard project is built on. - pandas must be installed to run these examples locally (
pip install pandas) — every graded example in this course (quiz, exercises, practice, challenges) runs it for you already, in-browser via Pyodide.
csv.DictReader: open a sales file, loop over every row, and manually accumulate totals, one dictionary at a time. That approach works, but the moment the question changes — "now break it down by region," "now find the top 3 products," "now handle a blank cell" — you're writing a new loop every time. pandas exists to make exactly this kind of tabular, real-world data work fast, short, and far less error-prone.
1. What pandas is, and why it exists
- pandas provides two core types built on top of NumPy: the Series (a single labeled column of data) and the DataFrame (a labeled table made of multiple Series, one per column).
- A NumPy array is homogeneous — every element shares one
dtype. A DataFrame is heterogeneous by column — one column can hold text, the next numbers, the next dates, all in the same table. - Every row and column has a label (a row index, a column name), not just a numeric position — that labeling is the core difference from a raw NumPy array.
DataFrame (a labeled, 2D table) and Series (a labeled, 1D column) types, plus a large set of methods for reading, cleaning, filtering, and summarizing tabular data. It's installed with pip install pandas and conventionally imported as import pandas as pd. Internally, each DataFrame column is backed by a NumPy array, so pandas inherits NumPy's speed while adding labels and mixed column types on top.
Here's the concrete motivating example this whole chapter builds on: a small table of sales records, and a real question — "what's the total revenue?" — asked the pandas way.
import pandas as pd
sales = pd.DataFrame({
"product": ["Widget", "Gadget", "Gizmo"],
"units_sold": [40, 25, 61],
"revenue": [1200, 950, 1830],
})
print(sales)
print("Total revenue:", sales["revenue"].sum())
product units_sold revenue
0 Widget 40 1200
1 Gadget 25 950
2 Gizmo 61 1830
Total revenue: 3980
Notice the printed table: pandas shows a row index on the left
(0, 1, 2, auto-generated here)
and column names across the top (product,
units_sold, revenue) — both are
labels, and both can be used to look values back up, which
Sub-topic 4 covers in depth.
sales["revenue"] is a Series. A DataFrame is a whole labeled table made of one or more Series sharing the same row index — sales itself is a DataFrame. Pulling a single column out of a DataFrame always gives back a Series.
- A NumPy array from Chapter 23 needed every value to share one type; this same sales table couldn't exist as a single NumPy array, since
productis text andrevenueis numbers. sales["revenue"].sum()reads almost like English — "the revenue column, summed" — and it's exactly that.- Every pandas column is still a NumPy array underneath, so the vectorized instincts from Chapter 23 (no explicit loops for math) carry forward directly.
Go Deeper: does pandas replace NumPy, then?
No — pandas is built on top of NumPy, not instead of it. Reach for a plain NumPy array when data is genuinely uniform and numeric (a grid of sensor readings, a matrix for math). Reach for a pandas DataFrame the moment the data has meaningful column names, mixed types across columns, or naturally comes from a spreadsheet/CSV/database table — which describes most real-world business and reporting data.
- pandas provides
Series(one labeled column) andDataFrame(a labeled table of columns), both built on top of NumPy. - A DataFrame is heterogeneous by column (mixed types across columns); a NumPy array is homogeneous (one type for the whole array).
- Every row and column has a label, not just a numeric position — the core new idea pandas adds over NumPy.
2. Creating a DataFrame
pd.DataFrame(a_dict_of_lists)builds a table from Python data already in memory — each dict key becomes a column name.pd.read_csv(path_or_buffer)builds a table directly from a CSV file (or CSV-format text), inferring column names and types automatically.- Compared to Chapter 13's
csvmodule,read_csv()replaces an entire open-loop-parse-accumulate pattern with one function call.
read_csv() is usually the very first line of a real pandas script.
import pandas as pd
df1 = pd.DataFrame({
"product": ["Widget", "Gadget", "Gizmo"],
"region": ["East", "West", "East"],
"revenue": [1200, 950, 1830],
})
print("From a dict of lists:")
print(df1)
From a dict of lists:
product region revenue
0 Widget East 1200
1 Gadget West 950
2 Gizmo East 1830
That works fine for data you've already typed out by hand. The far more common case is data that already exists as a CSV file — and this is where pandas pays off against Chapter 13's approach immediately:
import csv
from io import StringIO
import pandas as pd
csv_text = """product,region,revenue
Widget,East,1200
Gadget,West,950
Gizmo,East,1830
Widget,West,700
"""
# The Chapter 13 way: open, loop, parse, accumulate by hand
total_csv_module = 0
for row in csv.DictReader(StringIO(csv_text)):
total_csv_module += int(row["revenue"])
print("csv module total revenue:", total_csv_module)
# The pandas way: one function call, one column call
df = pd.read_csv(StringIO(csv_text))
print("pandas total revenue:", df["revenue"].sum())
csv module total revenue: 4680
pandas total revenue: 4680
Both approaches reach the identical answer — the payoff is in
what each one costs to write and extend. The csv module
needed a manual loop, a manual int() conversion, and a
manual running total, all written by hand. read_csv()
replaced the file-opening, the row-looping, and the type conversion
in one call, and .sum() replaced the accumulator entirely.
Reading a real file on disk looks the same, just with a filename
instead of StringIO:
import pandas as pd
df = pd.read_csv("sales.csv") # reads a real file from disk
print(df.head())
StringIO?
io.StringIO wraps a plain Python string so it behaves like an open file — useful for testing read_csv() against CSV-format text without needing a real file on disk. In production code, pd.read_csv("sales.csv") reads directly from a real path, exactly like the open() calls Chapter 13 already taught.
pd.DataFrame(dict_of_lists)is the right tool for data already in Python memory.pd.read_csv()is the right tool for data living in a CSV file — it replaces an entire manual open/loop/parse pattern.- Both produce the exact same kind of object: a DataFrame, ready for every method the rest of this chapter covers.
Go Deeper: what other formats can pandas read besides CSV?
pandas ships matching readers for most common tabular formats:
pd.read_excel(), pd.read_json(),
pd.read_sql() (working directly with the database
connections Chapter 21 covered), and more. They all follow the
same shape — call the reader, get back a DataFrame —
so everything this chapter teaches from here on works
identically no matter which reader produced the DataFrame.
pd.DataFrame(dict_of_lists)builds a table from Python data already in memory.pd.read_csv()builds a table directly from a CSV file or CSV-format text, inferring columns and types.- Against Chapter 13's
csvmodule,read_csv()plus a column method like.sum()replaces an entire manual loop-and-accumulate pattern.
3. Inspecting data
.head(n)/.tail(n)show the first/lastnrows (default 5) — the fastest sanity check after loading any dataset..info()prints column names, non-null counts, and dtypes in one summary;.describe()prints count/mean/std/min/max/quartiles for every numeric column..shape,.columns, and.dtypesgive the row/column count, the column names, and each column's data type.
import pandas as pd
from io import StringIO
csv_text = """product,region,units_sold,revenue
Widget,East,40,1200
Gadget,West,25,950
Gizmo,East,61,1830
Widget,West,18,700
Gadget,East,33,1100
Gizmo,West,9,310
"""
df = pd.read_csv(StringIO(csv_text))
print("df.head(2):")
print(df.head(2))
print()
print("df.shape:", df.shape)
print("df.columns:", list(df.columns))
df.head(2):
product region units_sold revenue
0 Widget East 40 1200
1 Gadget West 25 950
df.shape: (6, 4)
df.columns: ['product', 'region', 'units_sold', 'revenue']
.shape reads exactly like a NumPy array's .shape
from Chapter 23 — (6, 4) is 6 rows, 4 columns —
since a DataFrame's shape follows the same convention. .dtypes
and .info() go one level deeper, per-column:
import pandas as pd
from io import StringIO
csv_text = """product,region,units_sold,revenue
Widget,East,40,1200
Gadget,West,25,950
Gizmo,East,61,1830
"""
df = pd.read_csv(StringIO(csv_text))
print("df.dtypes:")
print(df.dtypes)
print()
df.info()
df.dtypes:
product str
region str
units_sold int64
revenue int64
dtype: object
<class 'pandas.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 4 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 product 3 non-null str
1 region 3 non-null str
2 units_sold 3 non-null int64
3 revenue 3 non-null int64
dtypes: int64(2), str(2)
memory usage: 228.0 bytes
.info()'s "Non-Null Count"?
A null value in pandas represents missing data (shown as NaN). "Non-Null Count" is how many rows in that column actually have a real value — if it's lower than the total row count, that column has missing data somewhere, which Sub-topic 5 covers in depth.
.describe() goes further still, computing real summary
statistics — the same .mean()/.std()/.min()/.max()
idioms from Chapter 23, run automatically over every numeric column
at once:
import pandas as pd
from io import StringIO
csv_text = """product,region,units_sold,revenue
Widget,East,40,1200
Gadget,West,25,950
Gizmo,East,61,1830
Widget,West,18,700
Gadget,East,33,1100
Gizmo,West,9,310
"""
df = pd.read_csv(StringIO(csv_text))
print(df.describe())
units_sold revenue
count 6.000000 6.000000
mean 31.000000 1015.000000
std 18.297541 511.106642
min 9.000000 310.000000
25% 19.750000 762.500000
50% 29.000000 1025.000000
75% 38.250000 1175.000000
max 61.000000 1830.000000
.head()/.tail()are the fastest first look at any newly loaded DataFrame..info()answers "what columns exist, and are any missing values?" in one call..describe()answers "what do the numbers actually look like?" — count, mean, spread, and range — for every numeric column at once.
Go Deeper: does .describe() include text columns?
By default, .describe() only summarizes numeric
columns, since "mean" and "std" don't make sense for text.
Passing include="all" adds text columns too, showing
count, unique, top (the
most frequent value), and freq instead of numeric
statistics for those columns.
.head()/.tail()preview the first/last rows;.shape/.columns/.dtypesdescribe the table's structure..info()summarizes columns, non-null counts, and dtypes in one call — the fastest way to spot missing data..describe()computes count/mean/std/min/max/quartiles for every numeric column at once.
4. Selecting, filtering & .loc[] vs. .iloc[]
df['col']selects one column (a Series);df[['col1', 'col2']]selects several columns at once (a DataFrame).df[df['col'] > x]is boolean filtering — the direct DataFrame equivalent of Chapter 23's NumPy boolean masking..loc[]selects by label (row index value, column name);.iloc[]selects by integer position, regardless of what the labels actually are.
.loc[] and .iloc[] is the single most common pandas beginner mistake — and it fails silently (wrong row, no error) far more often than it raises a clean exception, which makes it worth slowing down for.
Column selection first, since it's the most immediately useful:
import pandas as pd
from io import StringIO
csv_text = """product,region,units_sold,revenue
Widget,East,40,1200
Gadget,West,25,950
Gizmo,East,61,1830
Widget,West,18,700
"""
df = pd.read_csv(StringIO(csv_text))
print("df['product']:")
print(df['product'])
print()
print("df[['product', 'revenue']]:")
print(df[['product', 'revenue']])
df['product']:
0 Widget
1 Gadget
2 Gizmo
3 Widget
Name: product, dtype: str
df[['product', 'revenue']]:
product revenue
0 Widget 1200
1 Gadget 950
2 Gizmo 1830
3 Widget 700
Notice the shape difference: one pair of brackets with a single column name returns a Series; double brackets with a list of names returns a DataFrame, even if that list only has one name in it.
Boolean filtering works exactly like Chapter 23's array masking, just with a whole row kept or dropped instead of a single value:
import pandas as pd
from io import StringIO
csv_text = """product,region,units_sold,revenue
Widget,East,40,1200
Gadget,West,25,950
Gizmo,East,61,1830
Widget,West,18,700
"""
df = pd.read_csv(StringIO(csv_text))
print("df[df['revenue'] > 1000]:")
print(df[df['revenue'] > 1000])
df[df['revenue'] > 1000]:
product region units_sold revenue
0 Widget East 40 1200
2 Gizmo East 61 1830
Before any explanation, here's the exact picture that separates
.loc[] from .iloc[] — the same
3-row table, with an explicit, non-numeric row index:
product revenue
r1 Widget 1200
r2 Gadget 950
r3 Gizmo 1830
df.loc['r2'] -- find the row LABELED 'r2' -> Gadget, 950
df.iloc[1] -- find the row at POSITION 1 -> Gadget, 950
(position 1 happens to BE 'r2' here,
but .loc['r2'] would still work even
if the rows were reordered -- .iloc[1] would not)
With the picture in place: .loc[] always means "look
this label up," and .iloc[] always means "count to
this position," no matter what the labels actually are.
import pandas as pd
from io import StringIO
csv_text = """product,revenue
Widget,1200
Gadget,950
Gizmo,1830
"""
df = pd.read_csv(StringIO(csv_text))
df.index = ["r1", "r2", "r3"]
print(df)
print()
print("df.loc['r2']:")
print(df.loc['r2'])
print()
print("df.iloc[1]:")
print(df.iloc[1])
print()
print("df.loc['r2', 'revenue']:", df.loc['r2', 'revenue'])
print("df.iloc[1, 1]:", df.iloc[1, 1])
product revenue
r1 Widget 1200
r2 Gadget 950
r3 Gizmo 1830
df.loc['r2']:
product Gadget
revenue 950
Name: r2, dtype: object
df.iloc[1]:
product Gadget
revenue 950
Name: r2, dtype: object
df.loc['r2', 'revenue']: 950
df.iloc[1, 1]: 950
0, 1, 2, .... In that specific, common case, .loc[1] and .iloc[1] happen to return the same row, since the label and the position are the same number — which is exactly why the distinction is easy to miss until the index becomes something else (a product name, a date, or rows that have been filtered/sorted so their positions no longer line up with their original labels).
df['col']returns a Series;df[['col1', 'col2']]returns a DataFrame, even for a single-item list.df[df['col'] > x]filters rows with a boolean condition, no loop needed — the DataFrame version of Chapter 23's array masking..loc[label]looks up by row/column label;.iloc[position]looks up by integer position — they only look interchangeable when the index happens to be plain0, 1, 2, ....
Go Deeper: why does .loc[] with a slice behave differently from .iloc[] with a slice?
df.iloc[0:2] behaves like a normal Python slice —
it excludes the end position, returning rows at positions 0 and 1
only. df.loc['r1':'r2'] is inclusive of the
end label — it returns every row from 'r1'
through 'r2', including 'r2' itself.
This is a deliberate, documented pandas design choice (label
slicing is inclusive; position slicing is not), not a bug —
but it's exactly the kind of detail that trips people up if
they've only ever tested with a default integer index.
- Single brackets with one column name return a Series; double brackets with a list return a DataFrame.
- Boolean filtering (
df[df['col'] > x]) keeps only matching rows, with no explicit loop. .loc[]is label-based;.iloc[]is position-based — they agree only when the index is the default0, 1, 2, ....
5. Adding columns & handling missing data
- Assigning to a new column name (
df['new_col'] = ...) adds it, computed from existing columns with the same vectorized style as Chapter 23's arrays. - Missing values show up as
NaN(Not a Number);.isna()finds them,.dropna()removes rows containing them,.fillna()replaces them with a chosen value. - Real-world CSVs almost always have at least some missing cells — a blank field, an unrecorded reading — so this is a genuine, common first encounter with messy data, not a hypothetical edge case.
import pandas as pd
df = pd.DataFrame({
"product": ["Widget", "Gadget", "Gizmo"],
"units_sold": [40, 25, 61],
"unit_price": [30, 38, 30],
})
df["revenue"] = df["units_sold"] * df["unit_price"]
print(df)
product units_sold unit_price revenue
0 Widget 40 30 1200
1 Gadget 25 38 950
2 Gizmo 61 30 1830
df["units_sold"] * df["unit_price"] multiplies the two
columns element-by-element — the exact same vectorized idea as
Chapter 23's arr1 * arr2, since each column is a NumPy
array underneath. Now the messier, more realistic case — a CSV
with a couple of blank cells:
import pandas as pd
from io import StringIO
csv_text = """product,region,revenue
Widget,East,1200
Gadget,,950
Gizmo,East,
Widget,West,700
"""
df = pd.read_csv(StringIO(csv_text))
print(df)
print()
print("df.isna():")
print(df.isna())
product region revenue
0 Widget East 1200.0
1 Gadget NaN 950.0
2 Gizmo East NaN
3 Widget West 700.0
df.isna():
product region revenue
0 False False False
1 False True False
2 False False True
3 False False False
Notice revenue printed as 1200.0 instead
of 1200 — a column can't mix a real integer and
NaN (which is technically a float), so pandas silently
upgrades the whole column to float64 the moment any
value is missing. From here, .dropna() and
.fillna() are the two ways to actually handle it:
import pandas as pd
from io import StringIO
csv_text = """product,region,revenue
Widget,East,1200
Gadget,,950
Gizmo,East,
Widget,West,700
"""
df = pd.read_csv(StringIO(csv_text))
print("df.dropna():")
print(df.dropna())
print()
print("df.fillna({'region': 'Unknown', 'revenue': 0}):")
print(df.fillna({"region": "Unknown", "revenue": 0}))
df.dropna():
product region revenue
0 Widget East 1200.0
3 Widget West 700.0
df.fillna({'region': 'Unknown', 'revenue': 0}):
product region revenue
0 Widget East 1200.0
1 Gadget Unknown 950.0
2 Gizmo East 0.0
3 Widget West 700.0
NaN?
NaN ("Not a Number") is pandas/NumPy's placeholder for a missing value. It behaves unusually in comparisons — NaN == NaN is actually False — which is exactly why .isna() exists as a dedicated check instead of comparing to NaN directly.
Choosing between .dropna() and .fillna()
is a real decision, not a mechanical one: .dropna()
discards the whole row, which is safe when missing data is rare and
the row is otherwise unreliable; .fillna() keeps the
row with a sensible default, which is better when losing that row's
other columns (like a real sale that just has a blank region) would
throw away useful information.
df['new_col'] = expressionadds a computed column, vectorized across every row..isna()finds missing values; a column with any missing values gets silently upgraded tofloat64..dropna()removes rows with any missing value;.fillna(value_or_dict)replaces missing values with a chosen default, per-column if given a dict.
Go Deeper: can .fillna() use something smarter than a fixed value?
Yes — a very common real pattern is
df['revenue'].fillna(df['revenue'].mean()), filling
missing values with that column's own average rather than a flat
0. This avoids dragging the total down to zero for a
row that's simply missing a number, while still keeping the row
in the dataset for its other columns.
- Assigning to a new column name adds it, computed vectorized from existing columns.
- Missing values show up as
NaN;.isna()finds them, and any missing value upgrades that column tofloat64. .dropna()removes incomplete rows;.fillna()replaces missing values with a chosen default instead.
6. Grouping, aggregation & sorting
df.groupby('col')splits a DataFrame into one group per unique value incol— nothing is computed yet until an aggregate method is called on it..sum()/.mean()/.agg()after agroupby()compute one result per group — the pandas equivalent of Chapter 23'saxis=aggregates, but grouped by a label instead of a row/column position..sort_values('col')reorders rows by a column's values, ascending by default.
groupby()+aggregate expressions — this is the exact toolkit behind this chapter's sales-dashboard project.
import pandas as pd
from io import StringIO
csv_text = """product,region,revenue
Widget,East,1200
Gadget,West,950
Gizmo,East,1830
Widget,West,700
Gadget,East,1100
Gizmo,West,310
"""
df = pd.read_csv(StringIO(csv_text))
print("df.groupby('region')['revenue'].sum():")
print(df.groupby('region')['revenue'].sum())
df.groupby('region')['revenue'].sum():
region
East 4130
West 1960
Name: revenue, dtype: int64
That's "one total per region" in a single line — no manual
loop grouping rows by hand. .agg() generalizes this to
multiple statistics at once, per group:
import pandas as pd
from io import StringIO
csv_text = """product,region,revenue
Widget,East,1200
Gadget,West,950
Gizmo,East,1830
Widget,West,700
Gadget,East,1100
Gizmo,West,310
"""
df = pd.read_csv(StringIO(csv_text))
print("df.groupby('product').agg({'revenue': ['sum', 'mean']}):")
print(df.groupby('product').agg({'revenue': ['sum', 'mean']}))
print()
print("df.sort_values('revenue', ascending=False):")
print(df.sort_values('revenue', ascending=False))
df.groupby('product').agg({'revenue': ['sum', 'mean']}):
revenue
sum mean
product
Gadget 2050 1025.0
Gizmo 2140 1070.0
Widget 1900 950.0
df.sort_values('revenue', ascending=False):
product region revenue
2 Gizmo East 1830
0 Widget East 1200
4 Gadget East 1100
1 Gadget West 950
3 Widget West 700
5 Gizmo West 310
groupby() works in three conceptual steps: split the DataFrame into groups by the given column's values, apply an aggregate function to each group independently, then combine the per-group results back into one table. You never see the split step directly — it happens the moment you call .sum(), .mean(), or .agg() on the grouped object.
Chaining a groupby() aggregate straight into
.sort_values() is exactly how a "top N" report gets
built — group by product, sum the revenue, then sort
descending to see the best performers first, which is precisely
what this chapter's project does.
df.groupby('col')splits rows into groups by that column's unique values.- An aggregate call after
groupby()—.sum(),.mean(), or.agg({...})for multiple statistics at once — computes one result per group. .sort_values('col', ascending=False)reorders rows, most useful right after an aggregate to surface the top or bottom performers.
Go Deeper: can you group by more than one column at once?
Yes — df.groupby(['region', 'product'])['revenue'].sum()
groups by every unique combination of region and product,
giving a more finely broken-down total (e.g. Widget sales in East
vs. Widget sales in West, reported separately) instead of
collapsing across one dimension at a time.
df.groupby('col')splits rows into groups by that column's values; nothing computes until an aggregate is called..sum()/.mean()/.agg({...})compute one (or several) results per group..sort_values('col', ascending=False)reorders rows — commonly chained right after a groupby aggregate to build a "top N" report.
- pandas is the default tool for business reporting and analytics in Python — sales dashboards, financial summaries, and A/B test analysis are almost always built on DataFrames.
- Data scientists and analysts spend a large share of real working time exactly in Sub-topic 5's territory — cleaning messy, real-world data with missing or malformed values before any actual analysis can happen.
groupby()is the everyday tool behind "break this down by region/product/day" — the single most common shape of question a stakeholder asks about any dataset.
Points to Remember
- pandas provides
Series(one labeled column) andDataFrame(a labeled table of columns), built on top of NumPy, to represent heterogeneous, real-world tabular data. pd.DataFrame(dict_of_lists)builds a table from Python data in memory;pd.read_csv()builds one from a CSV file, replacing an entire manualcsv-module loop with one call..head()/.info()/.describe()/.shape/.columns/.dtypesare the standard first look at any newly loaded DataFrame.df['col']/df[['col1','col2']]select columns;df[df['col'] > x]filters rows;.loc[]selects by label while.iloc[]selects by position — they only agree when the index is the default0, 1, 2, ....- Assigning to a new column name adds a computed column;
.isna()/.dropna()/.fillna()find and handle missing (NaN) data. .groupby('col')plus an aggregate (.sum()/.mean()/.agg()) computes one result per group;.sort_values()reorders rows, commonly chained right after to build a "top N" report.- Every pandas column is a NumPy array underneath — the vectorized, no-explicit-loop instincts from Chapter 23 carry forward directly into every method this chapter covered.