🐍 Python for Everyone

← Back to all chapters

Chapter 24 of 28 Intermediate 80 min read

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

Picture Chapter 13's 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.
Sub-topic 1 of 6

1. What pandas is, and why it exists

At a glance
  • 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.
Why this matters: nearly every real dataset — sales records, student rosters, sensor logs with timestamps — mixes text and numbers in the same table. NumPy alone can't represent that naturally; pandas exists specifically to close that gap while keeping NumPy's speed underneath.
What is... pandas? pandas is a Python library providing the 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.

first_dataframe.py
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())
actual output of first_dataframe.py
  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.

What is... a Series vs. a DataFrame? A Series is one labeled column — 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.
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.

Quick recap
  • pandas provides Series (one labeled column) and DataFrame (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.
Sub-topic 2 of 6

2. Creating a DataFrame

At a glance
  • 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 csv module, read_csv() replaces an entire open-loop-parse-accumulate pattern with one function call.
Why this matters: almost every real dataset starts life as a CSV file (an export from a spreadsheet, a database, or another tool) — read_csv() is usually the very first line of a real pandas script.
creating_from_dict.py
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)
actual output of creating_from_dict.py
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:

csv_module_vs_pandas.py
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())
actual output of csv_module_vs_pandas.py
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:

read_real_csv.py
import pandas as pd

df = pd.read_csv("sales.csv")   # reads a real file from disk
print(df.head())
What is... 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.
try_it.py
Click "Run Code" — try adding a units_sold column and computing df['units_sold'].sum().
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.

Quick recap
  • 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 csv module, read_csv() plus a column method like .sum() replaces an entire manual loop-and-accumulate pattern.
Sub-topic 3 of 6

3. Inspecting data

At a glance
  • .head(n)/.tail(n) show the first/last n rows (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 .dtypes give the row/column count, the column names, and each column's data type.
Why this matters: the very first thing to do with any DataFrame — before filtering, grouping, or reporting anything — is to actually look at it. Skipping this step is how "revenue" silently turns out to be text instead of numbers three steps later.
inspecting_basics.py
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))
actual output of inspecting_basics.py
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:

dtypes_and_info.py
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()
actual output of dtypes_and_info.py
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
What is... .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:

describe_demo.py
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())
actual output of describe_demo.py
       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
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.

Quick recap
  • .head()/.tail() preview the first/last rows; .shape/.columns/.dtypes describe 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.
Sub-topic 4 of 6

4. Selecting, filtering & .loc[] vs. .iloc[]

At a glance
  • 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.
Why this matters: mixing up .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:

selecting_columns.py
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']])
actual output of selecting_columns.py
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:

boolean_filtering.py
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])
actual output of boolean_filtering.py
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:

.loc[] (by label) vs. .iloc[] (by position), on the same DataFrame
     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.

loc_vs_iloc.py
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])
actual output of loc_vs_iloc.py
   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
What is... the default row index? When a DataFrame is created without an explicit index (as every earlier example in this chapter did), pandas assigns a default RangeIndex — plain integers 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).
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.

Quick recap
  • 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 default 0, 1, 2, ....
Sub-topic 5 of 6

5. Adding columns & handling missing data

At a glance
  • 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.
Why this matters: a missing value silently breaks a sum or average if it isn't handled first — deciding whether to drop it or fill it in is a real judgment call this chapter's project has to make before computing any totals.
adding_a_column.py
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)
actual output of adding_a_column.py
  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:

missing_data.py
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())
actual output of missing_data.py
  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:

dropna_fillna.py
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}))
actual output of dropna_fillna.py
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
What is... 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.

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.

Quick recap
  • 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 to float64.
  • .dropna() removes incomplete rows; .fillna() replaces missing values with a chosen default instead.
Sub-topic 6 of 6

6. Grouping, aggregation & sorting

At a glance
  • df.groupby('col') splits a DataFrame into one group per unique value in col — nothing is computed yet until an aggregate method is called on it.
  • .sum()/.mean()/.agg() after a groupby() compute one result per group — the pandas equivalent of Chapter 23's axis= 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.
Why this matters: "total revenue by region," "top-selling products," "which items are underperforming" are all one-line groupby()+aggregate expressions — this is the exact toolkit behind this chapter's sales-dashboard project.
groupby_basics.py
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())
actual output of groupby_basics.py
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:

agg_and_sort.py
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))
actual output of agg_and_sort.py
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
What is... a "split-apply-combine" operation? 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.

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.

Quick recap
  • 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.
In the Real World

Points to Remember

← All Chapters Take the Quiz →