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
Read a CSV into a DataFrame and inspect it.
Select columns, and rows by label or by position.
Keep only the rows that match a stated condition.
pandas is the main tool for tabular data in this course. It is NumPy with column names and an index attached. Part D then applies all three steps to a real public dataset.
Load a real CSV and answer a question by filtering it.
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.
One labelled column: a NumPy array with an index (a label for each row).
Many Series side by side, forming the whole table.
Wes McKinney begins pandas at AQR Capital Management.
The firm lets him release it free to the public.
pandas becomes a sponsored project of a non-profit.
Released 21 January 2026; the version these slides use.
The name comes from panel data, an economics term for tables measured over time, and from “Python data analysis”.
pandas brings spreadsheet-style tables, with rows and named columns, to Python. Its numeric columns are stored as last week’s NumPy arrays.
downloads in September 2026: about 210 every second.
The creator’s own textbook, Python for Data Analysis (3rd ed.), is free to read online.
Open source and maintained by volunteers around the world.
Weeks 6 to 12 of this course all use pandas.
SourceDownloads: pypistats.org, without mirrors, retrieved 11 Oct 2026; book: wesmckinney.com/book; pandas.pydata.org/about
pandas’ table: rows and named columns, like a spreadsheet controlled with code.
e.g. df = pd.read_csv("cities.csv")
One column of a DataFrame: a NumPy array plus a label for each row.
e.g. df["pop"]
One named field that every row has — a vertical strip of the table.
e.g. city, region, pop
One record: all the values about one thing (one city, one project).
e.g. Cebu · Visayas · 964,000
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
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
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]
A True/False Series used inside df[ ] to keep only the rows where it is True.
e.g. df[df["pop"] > 1_000_000]
“Not a Number”: pandas’ marker for an empty cell. Summaries skip it; .isna() counts it.
e.g. a project with no start date
Writing several methods in a row, each working on the result of the one before.
e.g. df.sort_values("pop").head(3)
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.
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.
strpd.__version__the installed pandas: 3.0.5 on the laptop, 2.2.0 in the browsersys.maxsize > 2**32True on the laptop’s 64-bit Python, False in the browser’s 32-bit onet.dtypeseach column’s type: city is str on the laptop and object in the browserLoading 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.
read_csv parses the file and infers typesA 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 nicknamepd.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 columnsNames, 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| city | region | pop | |
|---|---|---|---|
| 0 | Cebu | Visayas | 964000 |
| 1 | Davao | Mindanao | 1777000 |
| 2 | Iloilo | Visayas | 457000 |
| 3 | Baguio | Luzon | 366000 |
| 4 | Tacloban | Visayas | 251000 |
df.columns, df.dtypesthe column names, then each column’s type: int64 = whole numbers, str = textdf.shape(rows, columns): the sizedf.describe().round()count, mean, spread (std), min, quartiles (the 25/50/75% marks) and max of every numeric column, rounded to whole numbersThe index labels rows; the columns name what each holds; a row is one record (one city). Selection works along both.
A DataFrame is a spreadsheet controlled with code, where the column names form the header row and the index labels stay with their row.
A single column pulled out is a Series: the NumPy array from week 5, with labels.
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.
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| city | region | pop | |
|---|---|---|---|
| 0 | Cebu | Visayas | 964000 |
| 1 | Davao | Mindanao | 1777000 |
| 2 | Iloilo | Visayas | 457000 |
| 3 | Baguio | Luzon | 366000 |
| 4 | Tacloban | Visayas | 251000 |
df["pop"]one name in the brackets: one column back, as a Seriesdf[["city", "pop"]]the inner brackets are a Python list of names; a list in → a smaller DataFrame out.loc by label, .iloc by positionThe slice rule differs: .loc[0:2] includes row 2;
.iloc[0:2] stops before it, like a normal Python slice.
.loc finds a guest by name badge and .iloc by seat number, so reordering the guests changes seat numbers but not badges.
Label known → .loc. Position known → .iloc.
The same slice, 0:2, goes to .loc and to .iloc.
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| city | region | pop | |
|---|---|---|---|
| 0 | Cebu | Visayas | 964000 |
| 1 | Davao | Mindanao | 1777000 |
| 2 | Iloilo | Visayas | 457000 |
| 3 | Baguio | Luzon | 366000 |
| 4 | Tacloban | Visayas | 251000 |
df.iloc[0, 1]row position 0, column position 1: columns count from 0, so city is 0, region 1 and pop 2df.loc[0:2, ["city", "pop"]]rows labelled 0 to 2, including 2, and two named columnsdf.iloc[0:2, [0, 2]]positions 0 and 1 (the end is excluded, as in a list slice), columns 0 and 2After filtering, the index keeps the original labels. This allows any row to be traced back, but differs from the expected 0, 1, 2.
Without drop=True the old index is kept as a new column, which is rarely intended.
df, the cities table from Part A| city | region | pop | |
|---|---|---|---|
| 0 | Cebu | Visayas | 964000 |
| 1 | Davao | Mindanao | 1777000 |
| 2 | Iloilo | Visayas | 457000 |
| 3 | Baguio | Luzon | 366000 |
| 4 | Tacloban | Visayas | 251000 |
small = df[df["pop"] < 500_000]keep the cities under half a million: Iloilo, Baguio and Taclobansmall.index.tolist()the row labels as a plain list: [2, 3, 4], the labels the three rows had in dfsmall.loc[0]raises KeyError: 0, since no row is labelled 0 any more; try/except (week 4) prints the error instead of stoppingreset_index(drop=True)give the rows fresh labels 0, 1, 2 and throw the old ones awayA 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| city | region | pop | |
|---|---|---|---|
| 0 | Cebu | Visayas | 964000 |
| 1 | Davao | Mindanao | 1777000 |
| 2 | Iloilo | Visayas | 457000 |
| 3 | Baguio | Luzon | 366000 |
| 4 | Tacloban | Visayas | 251000 |
df.loc[0]the row labelled 0, returned as a Series whose labels are the column namesdf.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 rowsWhat type does df["pop"] return?
B — a Series.
Single brackets with one name give a Series.
For a one-column DataFrame instead, use double brackets:
df[["pop"]].
One bracket → Series. Two brackets → DataFrame. The result type follows the brackets.
df["c"] Series · df[["c"]] DataFrame.
Next: keeping only the rows relevant to a question.
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 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| city | region | pop | |
|---|---|---|---|
| 0 | Cebu | Visayas | 964000 |
| 1 | Davao | Mindanao | 1777000 |
| 2 | Iloilo | Visayas | 457000 |
| 3 | Baguio | Luzon | 366000 |
| 4 | Tacloban | Visayas | 251000 |
df["pop"] > 1_000_000one True/False per row; the underscores in 1_000_000 are only there to make it readabledf[df["pop"] > 1_000_000]that Series inside df[ ]: keep the rows marked True, drop the restThis is Excel’s filter button with the rule written down, so re-running it gives the same rows.
& and |Use & for and, | for or — not the words
and/or. Each condition must be wrapped in parentheses because of operator precedence.
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| city | region | pop | |
|---|---|---|---|
| 0 | Cebu | Visayas | 964000 |
| 1 | Davao | Mindanao | 1777000 |
| 2 | Iloilo | Visayas | 457000 |
| 3 | Baguio | Luzon | 366000 |
| 4 | Tacloban | Visayas | 251000 |
big = df["pop"] > 500_000store the first rule as a True/False Series called big; vis is the second, and == tests for equalitydf[big & vis]& = and: rows where both are Truedf[big | vis]| (the vertical bar key) = or: rows where at least one is True& and | compare two masks one row at a timeEach condition gives one True or False per city, in the table’s row order. & is True where both masks are True; | where at least one is. df[mask] then keeps the True rows.
A NumPy mask selected array elements. A pandas mask selects whole rows, and its labels line it up with the table.
and and missing parentheses fail&, not andPython's and works on single True/False values, not on a whole Series. On a
Series it raises a ValueError.
& binds tighter than > (Python does & first), so
a > 5 & b < 3 groups wrongly. The correct form is
(a > 5) & (b < 3).
These two mistakes account for most early pandas errors. Once corrected, filtering becomes reliable.
Parenthesise each condition; join with & or |.
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.)
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).
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(…)a tiny 4-row frame with a text column g and a number column asub = t[t.g == "x"]the rows where g is "x" (two of them), as a new framesub["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]To change the original, the edit must be explicit: one .loc with the mask and the column, on df itself.
Filtering into a variable and editing that variable now provably does nothing to the original. This is safer, provided the behaviour is understood.
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 originalOn the left, the filter makes a new frame, sub, and the edit lands there. On the right, one .loc statement selects rows and column inside t and writes to t.
To change a table, assign through .loc on that table, in one statement.
pandas could not tell whether an object was a view or a copy, so it warned that an assignment might silently do nothing.
Copy-on-Write removed the ambiguity: a filter is always a copy.
Use one .loc[mask, col] = value on the frame to be modified. Correct on both versions.
A SettingWithCopyWarning is pandas 2.x’s message that a change might not reach the original table. Older notebooks, Stack Overflow answers (a question-and-answer website for programmers) and blog posts are full of .copy() calls added to silence this warning. They are harmless but no longer necessary.
value_counts() tallies a text column; .mean() and
describe() summarise numbers. Chained onto a filtered frame, they answer practical questions.
.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| city | region | pop | |
|---|---|---|---|
| 0 | Cebu | Visayas | 964000 |
| 1 | Davao | Mindanao | 1777000 |
| 2 | Iloilo | Visayas | 457000 |
| 3 | Baguio | Luzon | 366000 |
| 4 | Tacloban | Visayas | 251000 |
df["region"].value_counts()how many rows have each region, most common firstdf["pop"].mean()the average population across the rowsFiltering to one region, then sorting and taking the top row, covers this week's sequence (load, select, filter, summarise) in four lines.
.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| city | region | pop | |
|---|---|---|---|
| 0 | Cebu | Visayas | 964000 |
| 1 | Davao | Mindanao | 1777000 |
| 2 | Iloilo | Visayas | 457000 |
| 3 | Baguio | Luzon | 366000 |
| 4 | Tacloban | Visayas | 251000 |
vis = df[df["region"] == "Visayas"]filter: only the Visayan rowsvis["pop"].mean()the average population of those citiesvis.sort_values("pop").tail(1)sort smallest to biggest, then .tail(1) keeps the last row: the biggest cityLoad, 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.
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.
pd.read_csv(url)?pandas downloads with urllib, which this site’s bot protection answers with 403 Forbidden. requests gets through.
requests.get(url)download the whole dataset in one request, as in week 5pd.read_csv(io.StringIO(resp.text))the same read_csv as Part A, reading downloaded text instead of the cities textdffrom here on, df is the flood table; the cities table is replaced(34079, 15)34,079 projects, 15 columns.head() shows the values. .info() shows the types pandas has inferred, which are the source of most later errors.
Anything numeric showing str is text. Sorting, summing and comparing will all give wrong results without raising an error.
RangeIndex: 34079 entries, 0 to 3407834,079 rows, labelled 0 to 34,078Non-Null Counthow many cells in that column are filled in: start_date has 33,106, so 973 are missingstart_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 numbersmemory usage: 13.0 MBthe computer memory the table takes (MB = millions of bytes)A str column stores every row’s text, repeats included. A category column stores each distinct value once, plus small integer codes.
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() / 1e6total bytes used by every column (deep=True counts the text fully), divided by a million = megabytes: 13.6 MBdf[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 topicA 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.
Bad values become NaN instead of raising an error, so they can be counted and inspected.
df.budgeta shortcut for df["budget"]; it works when the column name has no spacespd.to_numeric(…, errors="coerce")turn text into numbers; anything that is not a number becomes NaN instead of crashingpd.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 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.
Without it, missing values come back as NaN rather than False, and using the result as a mask raises.
.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 charactersOnce a column is datetime64, .dt gives year, month, weekday and other components, each as an ordinary column that can be grouped.
On a text (str) column .dt raises. That error usually indicates that the pd.to_datetime step is missing.
df.start_date.min(), .max()the earliest and latest start dates in the table.dt.monththe month number (1–12) of each date1.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 countWeather does not explain this: a construction season would spread across the dry months, whereas this peaks in two. The likely cause is the budget release cycle, an administrative rather than a hydrological pattern.
Convert to datetime, then .dt.month.value_counts(). The accessor is designed for finding patterns like this.
Raw counts are hard to compare across datasets. normalize=True gives proportions instead.
"80.8% of projects are completed" is easier to interpret than "27,534 projects", which requires the reader to divide.
df.status.value_counts()a Series: each status (as the label) with its countnormalize=Truegive fractions of the total instead: 0.8079 = 80.79% of projectssort_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.
Sorting a DataFrame keeps whole rows, so the region and the description remain next to the number.
df.nlargest(3, "budget")the 3 whole rows with the biggest budget[["budget", "region"]]then keep only two columns for displaydf.nsmallest(3, "budget")the other end: the 3 smallest budgetsA readability choice, not a speed one. Long boolean expressions get hard to scan; query keeps them close to a spoken sentence.
No repeated df., no brackets around every clause. @name refers to a Python variable.
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 columnPython’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.
Use & | ~, and parenthesise every clause — & binds tighter than >.
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 oneUse a.empty, a.bool(), a.item(), a.any() or a.all()Python’s suggestions do not apply here; the fix is & with parenthesesdf[(…) & (…)]each condition in its own brackets, joined by &On numbers it reports quartiles. On a text (str) or category column it reports the four statistics relevant to text.
18 unique regions is a groupable column. 34,079 unique descriptions is free text, handled with .str, not groupby.
counthow many values are present (not missing)uniquehow many different values: 18 regionstop / freqthe most common value and how many times it appearsfillna 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.
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.
fillna("Not yet awarded")every missing contractor gets the same textfillna(df.budget.median())missing budgets get the middle budget of the whole tablegroupby("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.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).
apply is.True means both give the same answers.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 no vectorised equivalent exists, such as complex string parsing or a lookup with branching. It is a second choice, not a first.
budget = pd.Series(…)34,079 made-up budgets, as many as the flood table has rowsbudget.apply(lambda x: x / 1e6)run the little function 34,079 times, once per budgetbudget / 1e6the same division as one vectorised operation (week 5): the whole column at onceRead the flood CSV. Run .info(). List every column pandas guessed as str that should be numeric or a date.
Convert them with errors="coerce". Count what became NaN in each.
Filter to one region into sub. Assign a new column on sub. Check df — determine whether it changed. Then repeat the edit with .loc.
Which region has the highest median budget? Use groupby, then nlargest. Compare it with the region with the highest total.
In step 4, the region with the largest total and the region with the largest typical project usually differ, and that difference is the finding.
df.groupby("region").budget.median() — one median per region, as a SeriesAfter sub = df[df.region == "Region III"] and sub["flag"] = 1, what happens to df on pandas 3.x?
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.)df.loc[0:2] and df.iloc[0:2] on the same frame return different numbers of rows. Why?
.loc[0:2] gives 3 rows, .iloc[0:2] gives 2.Which keeps rows that are both big and Visayan?
df[big and vis]df[big & vis]df[big, vis]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.
& = and, | = or, each condition in parentheses.
Symbols, not words, for Series logic.
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.
.describe, column selection, boolean filters, isin, sort_values,
.loc/.iloc, value_counts, and a first taste of groupby.
Use .query("pop > 500000") as a readable filter alternative.
read_csv, then .head/.info/.describe before anything else.
Columns by name; rows by .loc (label) or .iloc (position).
A condition in brackets; combine with & / | and
parentheses.
In summary: read the file, inspect it, then keep the rows and columns the question requires.
Reduce a raw CSV to the subset required for a study.
object in pandas 2).isna().sum()df[mask]: keep the rows where the mask is True.sort_values().head().locFinish the Week 6 lab and submit it. Filtering with a combined condition should be possible from memory.
pandas "10 minutes to pandas" — pandas.pydata.org/docs/user_guide/10min.
Everything here is linked on the course page beside this deck.
Grouping, merging and reshaping, the core operations of pandas analysis.
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