DS 208 · Week 6

Data Manipulation with pandas I

The DataFrame, a spreadsheet controlled with code: loading a file, then selecting and filtering rows and columns.

Programming for Data Science · University of the Philippines Cebu

Outline

From a file to a selection of rows

Previous session

Arrays are fast but unlabelled

NumPy provides speed, but "column 2" carries no meaning for a reader. A DataFrame keeps that speed and adds names and an index so the data is self-describing.

A Series

One labelled column: a NumPy array with an index (a label for each row).

A DataFrame

Many Series side by side, forming the whole table.

About the tool

pandas was built inside an investment firm

2008

Started

Wes McKinney begins pandas at AQR Capital Management.

2009

Open source

The firm lets him release it free to the public.

2015

NumFOCUS

pandas becomes a sponsored project of a non-profit.

2026

pandas 3.0

Released 21 January 2026; the version these slides use.

Sourcepandas.pydata.org/about; Wikipedia: pandas (software)

About the tool

How widely pandas is used

SourceDownloads: pypistats.org, without mirrors, retrieved 11 Oct 2026; book: wesmckinney.com/book; pandas.pydata.org/about

Key terms

Ten terms introduced this week

DataFrame

pandas’ table: rows and named columns, like a spreadsheet controlled with code.

e.g. df = pd.read_csv("cities.csv")

Series

One column of a DataFrame: a NumPy array plus a label for each row.

e.g. df["pop"]

column

One named field that every row has — a vertical strip of the table.

e.g. city, region, pop

row

One record: all the values about one thing (one city, one project).

e.g. Cebu · Visayas · 964,000

index (label)

The labels down the left side that name each row. By default 0, 1, 2… and they stay with their row.

e.g. df.loc[0] is the row labelled 0

dtype

The type of one column. str is pandas’ word for text (object in pandas 2 and older notebooks).

e.g. pop is int64, city is str

.loc / .iloc

Two ways to pick rows and columns: .loc by label, .iloc by position (counting from 0).

e.g. df.loc[0, "city"], df.iloc[0, 0]

boolean filter

A True/False Series used inside df[ ] to keep only the rows where it is True.

e.g. df[df["pop"] > 1_000_000]

NaN (missing value)

“Not a Number”: pandas’ marker for an empty cell. Summaries skip it; .isna() counts it.

e.g. a project with no start date

method chaining

Writing several methods in a row, each working on the result of the one before.

e.g. df.sort_values("pop").head(3)

Runnable code

pandas also runs on these slides

As in week 5, a code block with a ▶ Run / Edit button runs in the browser, and the code can be changed and run again. The first run downloads Python and pandas into the page, which takes 10 to 20 seconds.

The browser has an older pandas

Printed outputs on the slides come from the lecture laptop, which runs pandas 3. The browser runs pandas 2.2, so text columns print as object instead of str, and the two copy slides in Part C print a warning that pandas 3 removed.

Key terms

object
pandas 2’s type name for a text column; pandas 3 calls it str
import io, sys print("pandas version:", pd.__version__) print("64-bit Python:", sys.maxsize > 2**32) t = pd.read_csv(io.StringIO("city,pop\nCebu,964000")) print(t.dtypes) pandas version: 3.0.5 64-bit Python: True city str pop int64 dtype: object
  • pd.__version__the installed pandas: 3.0.5 on the laptop, 2.2.0 in the browser
  • sys.maxsize > 2**32True on the laptop’s 64-bit Python, False in the browser’s 32-bit one
  • t.dtypeseach column’s type: city is str on the laptop and object in the browser
Part A

The DataFrame

Loading a file and inspecting it.

Week 5 applied maths to whole arrays. pandas places those arrays in a table with column names and row labels, a spreadsheet controlled with code.

Loading a CSV

read_csv parses the file and infers types

A CSV file (comma-separated values) is a plain-text table: one row per line, commas between the columns. Given one, pandas parses the header (the first line of column names), infers each column's type, and returns a DataFrame — a table of rows and named columns. .head() shows the first five rows.

  • csv_text = """…"""a small CSV file: a header line of column names, then one line per city (approximate 2020 census populations); pd is pandas’ usual nickname
  • pd.read_csv(io.StringIO(csv_text))read it into a DataFrame called df; io.StringIO makes text behave like an open file (week 5). With a file on disk this is pd.read_csv("cities.csv")
  • df.head(), df.shapea method (brackets): the first 5 rows; an attribute (no brackets): (5, 3) = 5 rows, 3 columns
import pandas as pd import io csv_text = """city,region,pop Cebu,Visayas,964000 Davao,Mindanao,1777000 Iloilo,Visayas,457000 Baguio,Luzon,366000 Tacloban,Visayas,251000""" df = pd.read_csv(io.StringIO(csv_text)) print(df.head()) print(df.shape) city region pop 0 Cebu Visayas 964000 1 Davao Mindanao 1777000 2 Iloilo Visayas 457000 3 Baguio Luzon 366000 4 Tacloban Visayas 251000 (5, 3)
Initial inspection

Four checks for every new dataset

Names, types, size and a summary are checked before any analysis. Wrong types at this stage cause later errors, exactly as in the Data Preparation phase of DS 227, the companion course.

df, the cities table from Part A

cityregionpop
0CebuVisayas964000
1DavaoMindanao1777000
2IloiloVisayas457000
3BaguioLuzon366000
4TaclobanVisayas251000
  • df.columns, df.dtypesthe column names, then each column’s type: int64 = whole numbers, str = text
  • df.shape(rows, columns): the size
  • df.describe().round()count, mean, spread (std), min, quartiles (the 25/50/75% marks) and max of every numeric column, rounded to whole numbers
print(df.columns.tolist()) print(df.dtypes) print(df.shape) print(df.describe().round()) ['city', 'region', 'pop'] city str region str pop int64 dtype: object (5, 3) pop count 5.0 mean 763000.0 std 628885.0 min 251000.0 25% 366000.0 50% 457000.0 75% 964000.0 max 1777000.0
Conceptual model

Structure of a DataFrame: index and columns

index city region pop 0 Cebu Visayas 964,000 1 Davao Mindanao 1,777,000 2 Iloilo Visayas 457,000 one column = a Series · one row = a record
Part B

Selecting

Columns, and rows by label or position.

Part A described the parts of a DataFrame. This part selects pieces of it (one column, several columns, or rows by label or position), as list indexing did in week 3, but with names.

Selecting columns

Single and double brackets

One name in single brackets gives a Series. A list of names in double brackets gives a smaller DataFrame. The double bracket is a list inside the select.

df, the cities table from Part A

cityregionpop
0CebuVisayas964000
1DavaoMindanao1777000
2IloiloVisayas457000
3BaguioLuzon366000
4TaclobanVisayas251000
print(df["pop"]) print(df[["city", "pop"]]) 0 964000 1 1777000 2 457000 3 366000 4 251000 Name: pop, dtype: int64 city pop 0 Cebu 964000 1 Davao 1777000 2 Iloilo 457000 3 Baguio 366000 4 Tacloban 251000
  • df["pop"]one name in the brackets: one column back, as a Series
  • df[["city", "pop"]]the inner brackets are a Python list of names; a list in → a smaller DataFrame out
Selecting rows

.loc by label, .iloc by position

df.loc[0:2] df.iloc[0:2] label city region pop 0 Cebu Visayas 964000 1 Davao Mindanao 1777000 2 Iloilo Visayas 457000 3 Baguio Luzon 366000 4 Tacloban Visayas 251000 label city region pop 0 Cebu Visayas 964000 1 Davao Mindanao 1777000 2 Iloilo Visayas 457000 3 Baguio Luzon 366000 4 Tacloban Visayas 251000 labels 0 to 2, end INCLUDED: 3 rows positions 0 and 1, end EXCLUDED: 2 rows position 2 (dashed) is where the slice stops
Exercise · 3 min

Labels compared with positions

The same slice, 0:2, goes to .loc and to .iloc.

Tasks

  1. Predict how many rows each of the last two lines prints.
  2. Select ▶ Run / Edit and run the code.
  3. Change both slices to 1:3. Which cities does each return now?

Result on the lecture laptop (select to reveal)

.loc[0:2] prints 3 rows (labels 0, 1 and 2); .iloc[0:2] prints 2. With 1:3, .loc returns Davao, Iloilo and Baguio, and .iloc returns Davao and Iloilo.

df, the cities table from Part A

cityregionpop
0CebuVisayas964000
1DavaoMindanao1777000
2IloiloVisayas457000
3BaguioLuzon366000
4TaclobanVisayas251000
print(df.loc[0, "region"]) # row label 0, column "region" print(df.iloc[0, 1]) # position 0, column position 1 print(df.loc[0:2, ["city", "pop"]]) print(df.iloc[0:2, [0, 2]])
  • df.iloc[0, 1]row position 0, column position 1: columns count from 0, so city is 0, region 1 and pop 2
  • df.loc[0:2, ["city", "pop"]]rows labelled 0 to 2, including 2, and two named columns
  • df.iloc[0:2, [0, 2]]positions 0 and 1 (the end is excluded, as in a list slice), columns 0 and 2
Worked example

Index labels are preserved after filtering

After filtering, the index keeps the original labels. This allows any row to be traced back, but differs from the expected 0, 1, 2.

reset_index(drop=True) for fresh numbering

Without drop=True the old index is kept as a new column, which is rarely intended.

df, the cities table from Part A

cityregionpop
0CebuVisayas964000
1DavaoMindanao1777000
2IloiloVisayas457000
3BaguioLuzon366000
4TaclobanVisayas251000
small = df[df["pop"] < 500_000] print(small.index.tolist()) print(small.iloc[0]["city"]) # position 0: works try: small.loc[0] # label 0: no such row now except KeyError as e: print("KeyError:", e) small = small.reset_index(drop=True) print(small.index.tolist()) [2, 3, 4] Iloilo KeyError: 0 [0, 1, 2]
  • small = df[df["pop"] < 500_000]keep the cities under half a million: Iloilo, Baguio and Tacloban
  • small.index.tolist()the row labels as a plain list: [2, 3, 4], the labels the three rows had in df
  • small.loc[0]raises KeyError: 0, since no row is labelled 0 any more; try/except (week 4) prints the error instead of stopping
  • reset_index(drop=True)give the rows fresh labels 0, 1, 2 and throw the old ones away
Row selection

A single row or all matching rows

A single row is selected by its label; a condition passed to .loc keeps every row where it is true. The second form is filtering (Part C).

df, the cities table from Part A

cityregionpop
0CebuVisayas964000
1DavaoMindanao1777000
2IloiloVisayas457000
3BaguioLuzon366000
4TaclobanVisayas251000
print(df.loc[0]) # the row labelled 0 print(df.iloc[-1]) # the row in the last position print(df.loc[df["city"] == "Cebu"]) city Cebu region Visayas pop 964000 Name: 0, dtype: object city Tacloban region Visayas pop 251000 Name: 4, dtype: object city region pop 0 Cebu Visayas 964000
  • df.loc[0]the row labelled 0, returned as a Series whose labels are the column names
  • df.iloc[-1]the row in the last position (-1 counts from the end, as with lists)
  • df.loc[df["city"] == "Cebu"]a True/False Series inside .loc keeps only the matching rows
Review question

Question (select to reveal the answer)

What type does df["pop"] return?

A · a DataFrame
B · a Series
C · a list
D · a single number

B — a Series.

Single brackets with one name give a Series. For a one-column DataFrame instead, use double brackets: df[["pop"]].

Break

  Five minutes

Next: keeping only the rows relevant to a question.

Part C

Filtering

Keep the rows that match a condition.

Week 5 selected array elements with a boolean mask. The same technique applies to a DataFrame, where it keeps whole rows.

Boolean filtering

A condition selects rows

Boolean filtering keeps rows by a rule. A comparison on a column gives a True/False Series. Inside the brackets, it keeps the rows where it is True: the NumPy mask applied to a table.

df, the cities table from Part A

cityregionpop
0CebuVisayas964000
1DavaoMindanao1777000
2IloiloVisayas457000
3BaguioLuzon366000
4TaclobanVisayas251000
print(df["pop"] > 1_000_000) print(df[df["pop"] > 1_000_000]) 0 False 1 True 2 False 3 False 4 False Name: pop, dtype: bool city region pop 1 Davao Mindanao 1777000
  • df["pop"] > 1_000_000one True/False per row; the underscores in 1_000_000 are only there to make it readable
  • df[df["pop"] > 1_000_000]that Series inside df[ ]: keep the rows marked True, drop the rest

This is Excel’s filter button with the rule written down, so re-running it gives the same rows.

Exercise · 3 min

Combine with & and |

Use & for and, | for or — not the words and/or. Each condition must be wrapped in parentheses because of operator precedence.

Tasks

  1. Predict which cities each of the two printed frames contains.
  2. Run the code.
  3. Change 500_000 to 400_000. Which of the two results changes?

Result on the lecture laptop (select to reveal)

big & vis keeps only Cebu; big | vis keeps Cebu, Davao, Iloilo and Tacloban. At 400_000, Iloilo (457,000) joins big & vis. big | vis does not change: Iloilo was already in it as a Visayan city.

df, the cities table from Part A

cityregionpop
0CebuVisayas964000
1DavaoMindanao1777000
2IloiloVisayas457000
3BaguioLuzon366000
4TaclobanVisayas251000
big = df["pop"] > 500_000 vis = df["region"] == "Visayas" print(df[big & vis]) print(df[big | vis])
  • big = df["pop"] > 500_000store the first rule as a True/False Series called big; vis is the second, and == tests for equality
  • df[big & vis]& = and: rows where both are True
  • df[big | vis]| (the vertical bar key) = or: rows where at least one is True
Masks, row by row

& and | compare two masks one row at a time

city pop region big pop > 500_000 mask vis region == "Visayas" mask big & vis both True mask big | vis at least one True mask Cebu 964,000 Visayas True True True True Davao 1,777,000 Mindanao True False False True Iloilo 457,000 Visayas False True False True Baguio 366,000 Luzon False False False False Tacloban 251,000 Visayas False True False True df[big & vis] keeps Cebu; df[big | vis] keeps 4 cities
Common error

Why and and missing parentheses fail

Change in pandas 3.0

A filtered frame is its own copy

pandas 3.0 made Copy-on-Write permanent. The old SettingWithCopyWarning is gone.

The previous slides only read from a DataFrame. This part covers changing one. Copy-on-Write means every filtered result behaves as its own copy. (The browser runs pandas 2.2, so code run on these slides and in the labs still shows the old warning.)

Worked example

Editing a filtered frame does not change the original

After filtering and assigning, the frame filtered from is unchanged. There is no warning and no ambiguity: the copy is guaranteed.

Filtering is like photocopying pages, since writing on the copy does not change the book; changing the book requires .loc (next slide).

Verified on pandas 3.0.5

Under pandas 2.x this same code printed a SettingWithCopyWarning and might or might not have written through. That uncertainty is what 3.0 removed.

t = pd.DataFrame({"g": ["x", "x", "y", "y"], "a": [1, 2, 3, 4]}) sub = t[t.g == "x"] sub["a"] = 99 print("sub:", sub.a.tolist()) print("t :", t.a.tolist()) sub: [99, 99] t : [1, 2, 3, 4]
  • t = pd.DataFrame(…)a tiny 4-row frame with a text column g and a number column a
  • sub = t[t.g == "x"]the rows where g is "x" (two of them), as a new frame
  • sub["a"] = 99set column a to 99 — in sub only
  • .tolist()turn a column into a plain Python list for printing: t.a is still [1, 2, 3, 4]
Worked example

Assigning through .loc on the target frame

To change the original, the edit must be explicit: one .loc with the mask and the column, on df itself.

One statement, not two

Filtering into a variable and editing that variable now provably does nothing to the original. This is safer, provided the behaviour is understood.

# t: the 4-row frame from the previous slide sub = t[t.g == "x"] sub["a"] = 99 # changes sub only t.loc[t.g == "x", "a"] = 77 # changes t itself print("t:", t.a.tolist()) t: [77, 77, 3, 4]
  • t.loc[t.g == "x", "a"] = 77rows where the mask is True, column a, on t itself: set to 77
  • [77, 77, 3, 4]the two "x" rows changed in the original
Two edits compared

Only an assignment on the frame itself changes it

sub = t[t.g == "x"]; sub["a"] = 99 t.loc[t.g == "x", "a"] = 77 sub g a x 99 x 99 t g a x 1 x 2 y 3 y 4 t g a x 77 x 77 y 3 y 4 t unchanged: the edit went into the copy t changed: [77, 77, 3, 4]
The old warning

SettingWithCopyWarning in pandas 2.x

Exercise · 3 min

Counting categories and summarising numbers

value_counts() tallies a text column; .mean() and describe() summarise numbers. Chained onto a filtered frame, they answer practical questions.

Tasks

  1. Predict the most common region and its count.
  2. Run the code.
  3. Change .mean() to .median(). Why is the result smaller?

Result on the lecture laptop (select to reveal)

Visayas, with 3 cities. The mean is 763000.0; the median is 457000.0, Iloilo’s population, the middle of the five. Davao’s 1,777,000 pulls the mean up but does not move the median.

df, the cities table from Part A

cityregionpop
0CebuVisayas964000
1DavaoMindanao1777000
2IloiloVisayas457000
3BaguioLuzon366000
4TaclobanVisayas251000
print(df["region"].value_counts()) print(df["pop"].mean())
  • df["region"].value_counts()how many rows have each region, most common first
  • df["pop"].mean()the average population across the rows
Exercise · 3 min

Finding the largest Visayan city

Filtering to one region, then sorting and taking the top row, covers this week's sequence (load, select, filter, summarise) in four lines.

Tasks

  1. Predict which city the last line prints.
  2. Run the code.
  3. Change .tail(1) to .head(1). Which city now, and why?

Result on the lecture laptop (select to reveal)

Cebu (964,000), the largest Visayan city; the Visayan mean is 557333.33. With .head(1) the first row after sorting is printed: Tacloban (251,000), the smallest.

df, the cities table from Part A

cityregionpop
0CebuVisayas964000
1DavaoMindanao1777000
2IloiloVisayas457000
3BaguioLuzon366000
4TaclobanVisayas251000
vis = df[df["region"] == "Visayas"] print(vis["pop"].mean()) print(vis.sort_values("pop").tail(1))
  • vis = df[df["region"] == "Visayas"]filter: only the Visayan rows
  • vis["pop"].mean()the average population of those cities
  • vis.sort_values("pop").tail(1)sort smallest to biggest, then .tail(1) keeps the last row: the biggest city
Part D

Case study: 34,079 flood control projects

Load, select and filter on a real public dataset.

The government’s (DPWH) list of flood control projects, the case study that closed week 5, now loaded as a DataFrame: 15 named columns instead of one array of budgets.

Loading the data

From the course API to a DataFrame

The download is the same as in week 5. Only the last step changes: pd.read_csv replaces csv.DictReader, so the result arrives with named columns and inferred types.

Why not pd.read_csv(url)?

pandas downloads with urllib, which this site’s bot protection answers with 403 Forbidden. requests gets through.

import io, requests url = "https://portal.latarak.com/api/flood/export.csv" resp = requests.get(url, timeout=60) df = pd.read_csv(io.StringIO(resp.text)) df.shape (34079, 15)
  • requests.get(url)download the whole dataset in one request, as in week 5
  • pd.read_csv(io.StringIO(resp.text))the same read_csv as Part A, reading downloaded text instead of the cities text
  • dffrom here on, df is the flood table; the cities table is replaced
  • (34079, 15)34,079 projects, 15 columns
Inspecting types

.info() reports types and memory in one call

.head() shows the values. .info() shows the types pandas has inferred, which are the source of most later errors.

Reading the Dtype column first

Anything numeric showing str is text. Sorting, summing and comparing will all give wrong results without raising an error.

df.info() RangeIndex: 34079 entries, 0 to 34078 Data columns (total 15 columns): # Column Non-Null Count Dtype 0 contract_id 34079 non-null str 4 budget 34079 non-null float64 8 start_date 33106 non-null str <- 10 year 34079 non-null int64 memory usage: 13.0 MB # excerpt: 4 of the 15 column rows
  • RangeIndex: 34079 entries, 0 to 3407834,079 rows, labelled 0 to 34,078
  • Non-Null Counthow many cells in that column are filled in: start_date has 33,106, so 973 are missing
  • start_date … str <-the dates are stored as text, not as dates — the arrow marks a column to fix (two slides on). budget is float64: already numbers
  • memory usage: 13.0 MBthe computer memory the table takes (MB = millions of bytes)
Memory and types

Converting three columns to category saves 2.3 MB

A str column stores every row’s text, repeats included. A category column stores each distinct value once, plus small integer codes.

Useful when values repeat

18 regions across 34,079 rows means each region name is stored about 1,893 times as text, and once as a category.

df.memory_usage(deep=True).sum() / 1e6 13.644672 # MB, as loaded for c in ["status", "region", "category"]: df[c] = df[c].astype("category") df.memory_usage(deep=True).sum() / 1e6 11.314324 # 17% smaller # and groupby gets faster too
  • df.memory_usage(deep=True).sum() / 1e6total bytes used by every column (deep=True counts the text fully), divided by a million = megabytes: 13.6 MB
  • df[c] = df[c].astype("category").astype converts a column to another dtype; the loop does it for three columns
  • # and groupby gets faster toogroupby = summarising per group (e.g. per region) — next week’s topic
Type conversion

Converting types at load time

A NaN (“Not a Number”) is pandas’ marker for a missing value. Types are converted immediately after reading the file, so all later code can assume they are correct.

errors="coerce" makes failures countable

Bad values become NaN instead of raising an error, so they can be counted and inspected.

df = pd.read_csv(io.StringIO(resp.text)) df["budget"] = pd.to_numeric(df.budget, errors="coerce") df["start_date"] = pd.to_datetime( df.start_date, errors="coerce") # how many refused? df.budget.isna().sum(), df.start_date.isna().sum() (0, 973) # 973 = the rows that were already blank
  • df.budgeta shortcut for df["budget"]; it works when the column name has no spaces
  • pd.to_numeric(…, errors="coerce")turn text into numbers; anything that is not a number becomes NaN instead of crashing
  • pd.to_datetime(…)the same for dates: text becomes a real date type (datetime64)
  • .isna().sum().isna() is True where a value is missing; summing counts them: (0, 973)
.str

String methods applied down a column

.str is an accessor: a doorway to a group of methods for one kind of column (text). With .str in front, the Python string methods work on all 34,079 rows at once and skip NaN instead of raising an error.

na=False on contains

Without it, missing values come back as NaN rather than False, and using the result as a mask raises.

df.description.str.contains("FLOOD", case=False, na=False).sum() 22,022 # 65% of all projects df.description.str.contains("REVETMENT", na=False).sum() 2,782 df.description.str.len().mean() 139.43490125883974 # chars # also: .lower() .strip() .split() # .replace() .startswith()
  • .str.contains("FLOOD", case=False, na=False)True where the description mentions flood, in any capitals; missing descriptions count as False
  • .sum()True counts as 1, so the sum is how many rows matched: 22,022
  • .str.len().mean()the length of every description, then their average: about 139 characters
.dt

Date components with .dt

Once a column is datetime64, .dt gives year, month, weekday and other components, each as an ordinary column that can be grouped.

Only works after conversion

On a text (str) column .dt raises. That error usually indicates that the pd.to_datetime step is missing.

df.start_date.min(), df.start_date.max() 2015-05-17 2025-09-23 df.start_date.dt.month.value_counts().sort_index() 1.0 1054 2.0 9416 <- 3.0 7122 <- 4.0 3972 ... 12.0 1041
  • df.start_date.min(), .max()the earliest and latest start dates in the table
  • .dt.monththe month number (1–12) of each date
  • 1.0, 2.0, …decimals, not whole numbers: the 973 missing dates have no month (NaN), and a number column with gaps is stored as floats
  • .value_counts().sort_index()method chaining: count each month, then order the result by month number instead of by count
Finding

Half of the flood projects start in February or March

0 2,500 5,000 7,500 10,000 Jan Feb 9,416 Mar 7,122 Apr May Jun Jul Aug Sep Oct Nov Dec February + March: 16,538 of 33,106 dated projects (50.0%)
Counting categories

value_counts with normalize=True

Raw counts are hard to compare across datasets. normalize=True gives proportions instead.

Percentages for reporting

"80.8% of projects are completed" is easier to interpret than "27,534 projects", which requires the reader to divide.

df.status.value_counts() Completed 27534 On-Going 5442 For Procurement 876 df.status.value_counts(normalize=True) Completed 0.8079 On-Going 0.1597 For Procurement 0.0257 # 80.8% — the honest headline figure
  • df.status.value_counts()a Series: each status (as the label) with its count
  • normalize=Truegive fractions of the total instead: 0.8079 = 80.79% of projects
Sorting and top-n

nlargest for the top rows

sort_values(...).head(n) is method chaining — sort, then take the first n — and it sorts all 34,079 rows to show three. nlargest does not.

Other columns are kept

Sorting a DataFrame keeps whole rows, so the region and the description remain next to the number.

df.nlargest(3, "budget")[["budget", "region"]] budget region 1,447,499,996 Central Office 1,096,255,230 Central Office 1,042,782,802 Central Office # ascending, for the other end df.nsmallest(3, "budget")
  • df.nlargest(3, "budget")the 3 whole rows with the biggest budget
  • [["budget", "region"]]then keep only two columns for display
  • df.nsmallest(3, "budget")the other end: the 3 smallest budgets
query()

The same filter written as a string

A readability choice, not a speed one. Long boolean expressions get hard to scan; query keeps them close to a spoken sentence.

Differences

No repeated df., no brackets around every clause. @name refers to a Python variable.

# bracket form df[(df.region == "Region III") & (df.budget > 1e8) & (df.status == "Completed")] # query form — same result df.query("region == 'Region III' " "and budget > 1e8 " "and status == 'Completed'") # with a variable floor = 1e8 df.query("budget > @floor")
  • df.query("region == 'Region III' and …")the filter written as one string; inside it, and is allowed
  • "…" "…"Python joins strings that sit side by side, so a long condition can span lines
  • @floor@ means “the Python variable called floor”, not a column
and vs &

The Series truth-value error

Python’s and wants a single True/False. A pandas mask is 34,079 of them, so it cannot decide, and the resulting message is difficult to interpret at first.

Two rules

Use & | ~, and parenthesise every clause — & binds tighter than >.

# wrong df[df.budget > 1e8 and df.status == "Completed"] ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() # right — note the parentheses df[(df.budget > 1e8) & (df.status == "Completed")] # also wrong: missing parens df[df.budget > 1e8 & df.status == ...] # & runs first, on the numbers
  • ValueError: The truth value of a Series is ambiguousread the last line: and asked the whole Series for one True/False, and pandas cannot choose one
  • Use a.empty, a.bool(), a.item(), a.any() or a.all()Python’s suggestions do not apply here; the fix is & with parentheses
  • df[(…) & (…)]each condition in its own brackets, joined by &
describe() on text

describe() output depends on dtype

On numbers it reports quartiles. On a text (str) or category column it reports the four statistics relevant to text.

The unique count

18 unique regions is a groupable column. 34,079 unique descriptions is free text, handled with .str, not groupby.

df.region.describe() count 34079 unique 18 top Region III freq 5412 # 5412/34079 = 16% in one region df.describe() # numeric only, by default df.describe(include="all") # everything
  • counthow many values are present (not missing)
  • uniquehow many different values: 18 regions
  • top / freqthe most common value and how many times it appears
Filling missing values

fillna takes a value, a method, or a rule

fillna replaces missing values (NaN) with a chosen value. Whether to fill at all is a judgement call (DS 227, the companion course, debates it). This slide covers how; the choice of fill value is itself a claim about the data.

Plausible fill values

A date is not filled with 0, nor a category with the mean. A fill must be a plausible member of that column, or it will distort every summary that follows.

# a constant df.contractor.fillna("Not yet awarded") # a computed value df.budget.fillna(df.budget.median()) # per group — usually more honest df.budget.fillna( df.groupby("region").budget.transform("median")) # count what you changed before = df.budget.isna().sum()
  • fillna("Not yet awarded")every missing contractor gets the same text
  • fillna(df.budget.median())missing budgets get the middle budget of the whole table
  • groupby("region").budget.transform("median")each missing budget gets its own region’s median (groupby is next week)
  • isna().sum()count the gaps before and after, to confirm how many were changed
Exercise · 4 min

apply is more than 100× slower for the same arithmetic

.apply() calls a Python function once per row. A lambda is a one-line function with no name: lambda x: x / 1e6 takes x and gives back x ÷ 1,000,000. A vectorised expression hands the whole column to NumPy’s fast C code at once (week 5).

Tasks

  1. Predict how many times slower apply is.
  2. Run the code. True means both give the same answers.
  3. Change 34_079 to 1_000. Does the gap stay the same?

Result on the lecture laptop (select to reveal)

2.2 ms against 0.013 ms: about 160×. With 1,000 budgets: 0.073 ms against 0.008 ms, only about 9×. Every call has a fixed start-up cost, so small columns hide the difference: week 5’s size rule.

When apply is appropriate

When no vectorised equivalent exists, such as complex string parsing or a lookup with branching. It is a second choice, not a first.

# time_ms(f) is week 5's timeit helper rng = np.random.default_rng(6) budget = pd.Series(rng.uniform(1e6, 1e9, 34_079)) # made-up def with_apply(): return budget.apply(lambda x: x / 1e6) def vectorised(): return budget / 1e6 print(with_apply().equals(vectorised())) print(f"apply : {time_ms(with_apply):.2f} ms") print(f"vectorised: {time_ms(vectorised):.3f} ms")
  • budget = pd.Series(…)34,079 made-up budgets, as many as the flood table has rows
  • budget.apply(lambda x: x / 1e6)run the little function 34,079 times, once per budget
  • budget / 1e6the same division as one vectorised operation (week 5): the whole column at once
Exercise · 8 min

Inspecting and filtering the flood data

1 · Load and inspect

Read the flood CSV. Run .info(). List every column pandas guessed as str that should be numeric or a date.

2 · Fix the types

Convert them with errors="coerce". Count what became NaN in each.

3 · Test the copy rule

Filter to one region into sub. Assign a new column on sub. Check df — determine whether it changed. Then repeat the edit with .loc.

4 · Answer one question

Which region has the highest median budget? Use groupby, then nlargest. Compare it with the region with the highest total.

Review question

Question (select to reveal the answer)

After sub = df[df.region == "Region III"] and sub["flag"] = 1, what happens to df on pandas 3.x?

A · It gains a flag column for the matching rows
B · Nothing — a filtered frame is its own copy under Copy-on-Write
C · A SettingWithCopyWarning is raised and the result is undefined
D · It raises a ValueError
B. pandas 3.0 made Copy-on-Write permanent, so a filter is always a copy and df is unchanged, with no warning. To change the original, use one statement: df.loc[df.region == "Region III", "flag"] = 1. (On pandas 2.x this same code raised SettingWithCopyWarning.)
Review question

Question (select to reveal the answer)

df.loc[0:2] and df.iloc[0:2] on the same frame return different numbers of rows. Why?

A · .loc skips rows containing NaN
B · .loc slices by label and includes the endpoint; .iloc slices by position and excludes it
C · .iloc is limited to two rows at a time
D · They are identical; any difference is a bug
B. Label slicing is inclusive because pandas cannot know what comes "after" an arbitrary label, so it includes the stated endpoint. Position slicing follows normal Python half-open convention. .loc[0:2] gives 3 rows, .iloc[0:2] gives 2.
Review question

Question (select to reveal the answer)

Which keeps rows that are both big and Visayan?

A · df[big and vis]
B · df[big & vis]
C · df[big, vis]
D · df[big | vis]

B — df[big & vis].

Element-wise AND on Series uses &. The word and (A) raises an error; | (D) is OR, not AND.

This week's lab

Load, select, filter a real CSV

The lab builds a small table of Philippine cities, inspects its types, selects columns, filters with single and combined conditions, sorts and counts to answer set questions. ~45 minutes.

Lab tasks

.describe, column selection, boolean filters, isin, sort_values, .loc/.iloc, value_counts, and a first taste of groupby.

Optional extension

Use .query("pop > 500000") as a readable filter alternative.

Summary

Loading, selecting and filtering

Glossary

Terms introduced this week

The DataFrame

DataFrame
pandas’ table of rows and named columns
Series
one column: values plus a label per row
column / row
one named field / one record
index (label)
the row labels down the left; they stay with their row
CSV / read_csv
a plain-text table with commas / the function that loads it
dtype / str
a column’s type / pandas’ word for text (object in pandas 2)
category
a dtype that stores each repeated value once
NaN (missing value)
the marker for an empty cell; count with .isna().sum()
errors="coerce"
turn values that will not convert into NaN instead of crashing
.head / .info / .describe
first rows / types and counts / summary numbers
accessor (.str / .dt)
text methods / date parts, applied down a whole column

Selecting, filtering, changing

.loc / .iloc
pick by label (end included) / by position (end left out)
boolean filter
df[mask]: keep the rows where the mask is True
& / | / ~
and / or / not, for True/False Series; wrap each condition in ( )
method chaining
methods in a row, each on the last result: .sort_values().head()
value_counts
how many rows have each value
nlargest / query
top-n rows by a column / a filter written as a string
fillna
replace missing values with a chosen value
apply / lambda
run a function on every value / a one-line nameless function
reset_index
give the rows fresh labels 0, 1, 2…
Copy-on-Write
every filtered result is its own copy; change the original with .loc
groupby
summarise per group, e.g. per region (next week)
Preparation for next week

Practice & reading

Next Week

pandas II: grouping, merging & reshaping

Split-apply-combine, joining two tables on a shared key, and pivoting long data into wide: the operations behind most analyses.

DS 208 · Programming for Data Science