# Only for Google Colab. On your own computer this cell does nothing: run it and go on.
# In Colab: run it first (about 1 minute and one automatic restart), then run it again until it prints "Ready".
import sys
if "google.colab" in sys.modules:
import importlib.metadata as md, os, subprocess, urllib.request, zipfile
os.chdir("/content")
if not os.path.isdir("DMA/S01_pandas_I"):
urllib.request.urlretrieve("https://albarran.github.io/DMA/sessions/S01_pandas_I.zip", "S01_pandas_I.zip")
zipfile.ZipFile("S01_pandas_I.zip").extractall()
if md.version("pandas") != "3.1.1":
r = subprocess.run([sys.executable, "-m", "pip", "install", "-q", *"pandas==3.1.1 pyarrow==26.0.1 openpyxl==3.1.5 matplotlib==3.11.2 seaborn==0.13.2 statsmodels==0.15.0 beautifulsoup4==4.15.0 lxml==6.1.3 fredapi==0.5.2 wbgapi==1.0.14 sdmx1==2.28.0 eurostat==1.1.1 duckdb==2.0.0 sqlalchemy==2.1.8 pymysql==1.2.4 rapidfuzz==3.14.6 missingno==0.5.2 openai==3.51.0 ollama==0.6.3 pydantic==2.14.3 bottleneck>=1.5".split()], capture_output=True, text=True)
if r.returncode != 0:
print(r.stderr[-1500:])
raise SystemExit("The installation failed: copy this message and send it to the lecturer.")
print("Installed. The session restarts now: run this cell again.")
os.kill(os.getpid(), 9)
os.chdir("DMA/S01_pandas_I")
print("Ready. Working directory:", os.getcwd())Session 1. The working environment and pandas I: one table
Preview of the notebook. To run it, download the session or open it in Colab.
Download session (zip) Open in Colab All sessions
This part of the course is about economic reasoning with data. Code is the means. The concepts of today (what a row is, what a variable is, how to select, create, sort, summarise and group) are the same in Python, R, Stata and SQL: learn the concept once and the syntax becomes a lookup.
Today:
| § | Block |
|---|---|
| 0 | Assessment and AI policy |
| 1 | The environment |
| 2 | pandas and its objects |
| 3 | Tidy data and the unit of observation |
| 4 | Types of variables |
| 5-9 | Basic operations: select and filter, create, sort, summarise, group |
| 10 | Averages and weights |
| 11 | Describe, predict, explain |
| 12 | Exercise |
| 13 | The same operations in every language |
Every block has two parts.
- Concept: the idea, when you use it and the general rule, valid in any language.
- Application: an economic question answered with the data, always in the same cycle:
- the question;
- before coding, the shape of the answer: one number or a table? how many rows?
- the minimal code;
- read the output;
- one sentence of conclusion, with its limit.
Languages. The class runs in Python, in this notebook. After each application, a block The same in R shows the operation in base R and in the tidyverse, with Stata where it helps: read it, there is nothing to run. The notebook S01_R.ipynb holds those same R blocks as cells you can run, with the same data and the same numbers (kernel R (DMA); in Colab, the button Open in Colab (R)). Open it at home, or in class if you already work in R and prefer to follow there. The exercises of §12 are the same in both notebooks: do them once, in the language you choose. In the tests you may answer in pandas, in R (base or dplyr) or in Stata.
If time; otherwise at home. The blocks with this label are the first to leave the class when time is short. They are part of the session: read and run them at home.
Data. A panel of countries from the World Bank’s World Development Indicators (WDI), 2000 to 2023, saved as a CSV file.
0. Assessment and AI policy
Part B is half of the course grade: short tests on paper, without a computer and without AI (20% of the course), and an individual project that you deliver as a notebook and then defend (30%). AI tools are allowed for practice and for the project; the tests and the defence show what you can explain without them. The details are on the course site: Assessment.
1. The environment
A notebook (.ipynb) mixes code cells, their output and text. Run a cell with Shift+Enter.
The kernel is the process that runs the cells: Python in this notebook, R in S01_R.ipynb. A notebook has one kernel.
The kernel remembers everything you have run, in the order you ran it, which may differ from the order of the cells on the screen. That is the main source of “it worked yesterday”.
Before you trust a result: Kernel → Restart Kernel and Run All Cells. If the notebook runs from top to bottom, the result is reproducible.
import sys
print(sys.executable) # which Python runs this kernelsys.executable should point to the course environment (see Setup on the course site; check_setup.ipynb prints ALL OK). If it points elsewhere, close Jupyter and start it again from the DMA folder as in the setup guide: uv run jupyter notebook, or conda activate dma and python -m notebook.
Files are read from the working directory unless you give a full path. Jupyter starts it in the folder of the notebook. Use relative paths: C:\Users\maria\Downloads\wdi.csv only works on María’s computer, data/wdi_panel.csv works on any.
from pathlib import Path
csv_file = Path("data") / "wdi_panel.csv"
Path.cwd(), csv_file.exists()Most “file not found” errors come from a different working directory: Path.cwd() is the first thing to check (in R, getwd(); in Stata, pwd).
2. pandas and its objects
Concept
Python by itself has no object for a table of data. pandas is the library that adds it. It is built on NumPy, the library for numerical arrays (fast vectors and matrices where all the elements have the same type).
pandas brings two objects:
- a Series: one column. A sequence of values of one type, each with a label. The labels are the index.
- a DataFrame: a table. Several Series of the same length that share one index. Each column is a variable and has its own type (numbers in one, text in another); each row is an observation.
The index holds the row labels. If you give none, it is the position: 0, 1, 2, … (Python counts from 0). pandas uses the index to identify rows, to select rows (by label with .loc, by position with .iloc; in base R, df["ESP", ] and df[1, ]; in SQL, WHERE iso3 = 'ESP') and to line up two objects label by label. The word has two other meanings that you will meet: a price index, and an SQL index (a structure that only speeds up searches).
The same objects exist wherever you work with data:
| Object | pandas | base R | tidyverse | Stata | SQL |
|---|---|---|---|---|---|
| One column | Series |
vector | vector | variable | column |
| A table | DataFrame |
data.frame |
tibble |
the dataset in memory | table |
| Row labels | index | row names (rarely used) | none: an identifier is one more column | none (_n is the position) |
the primary key |
- In R the table is part of the language: a
data.frameis a list of vectors of the same length. Base R is enough to work with it. - The tidyverse is a set of R packages (
dplyr,tidyr,readr,ggplot2, …) with one function per operation. Its table is the tibble, adata.framethat prints better and has no row names. - You will read code in both styles, so we show both.
Application
A Series and a DataFrame written by hand, from a dictionary (name: values). The figures are the unemployment rate (%) and the population (millions) of three countries in 2023.
import numpy as np
import pandas as pd
pd.__version__unemp = pd.Series([12.2, 7.3, 3.1], index=["ESP", "FRA", "DEU"], name="unemployment")
unempunemp["ESP"], unemp.mean() # one value by its label; a summary of the columnsmall = pd.DataFrame({"country": ["Spain", "France", "Germany"],
"unemployment": [12.2, 7.3, 3.1],
"population_m": [48.4, 68.4, 83.3]},
index=["ESP", "FRA", "DEU"])
smallprint(small.index) # row labels
print(small.columns) # column labels
print(small.dtypes) # one type per columntype(small["unemployment"]), type(small[["unemployment"]]) # one column: a Series; a list of columns: a DataFrameSelecting rows with the index: .loc by label, .iloc by position (Python counts from 0). In base R the same two selections are df["ESP", ] with row names and df[1, ] (R counts from 1).
small.loc["ESP"] # one row by its label: a Seriessmall.loc["ESP", "unemployment"], small.iloc[0, 1] # by label; by position (row 0, column 1)In practice you import a table from a file: pd.read_csv(), pd.read_excel(), pd.read_stata(), …
wdi = pd.read_csv(csv_file)
type(wdi)The same in R
# base R
unemp <- c(ESP = 12.2, FRA = 7.3, DEU = 3.1) # a named vector
unemp["ESP"]
mean(unemp)
small <- data.frame(country = c("Spain", "France", "Germany"),
unemployment = c(12.2, 7.3, 3.1),
population_m = c(48.4, 68.4, 83.3),
row.names = c("ESP", "FRA", "DEU"))
small$unemployment # one column: a vector
small["ESP", "unemployment"] # by row name and column name
small[1, 2] # by position (R counts from 1)
# tidyverse
library(tidyverse)
small_tbl <- tibble(country = c("Spain", "France", "Germany"),
unemployment = c(12.2, 7.3, 3.1),
population_m = c(48.4, 68.4, 83.3))
small_tbl
# importing the file
wdi_df <- read.csv("data/wdi_panel.csv", na.strings = "") # base R: a data.frame
wdi <- read_csv("data/wdi_panel.csv", show_col_types = FALSE) # tidyverse: a tibble
class(wdi_df)
class(wdi)A tibble is a data.frame, so base R syntax works on it: from here on the R blocks use wdi, the tibble (and wdi_df only where base R prints better).
Stata: import delimited "data/wdi_panel.csv", clear. In Part A the table was already inside the database: SELECT * FROM wdi.
3. Tidy data and the unit of observation
Concept
The first question about any table: what is one row?
The same unemployment rates (%), in two tables:
(A)
| country | year | unemployment |
|---|---|---|
| Spain | 2022 | 13.0 |
| Spain | 2023 | 12.2 |
| France | 2022 | 7.3 |
| France | 2023 | 7.3 |
(B)
| country | 2022 | 2023 |
|---|---|---|
| Spain | 13.0 | 12.2 |
| France | 7.3 | 7.3 |
| Euro area | 6.7 | 6.5 |
Questions for you (answer before reading on):
- What is one row in (A)? And in (B)?
- In (B), is
2023a variable or a value of the variable year? - In (B), is the row
Euro areaan observation of the same kind asSpain?
In Part A you designed relational tables: an entity described by its attributes, with a key that identifies each row. A tidy table (Wickham, 2014) is the same idea seen from the analysis side:
- each column is a variable;
- each row is an observation, all of the same kind;
- each cell is a value.
Table (B) is fine to show data and bad to analyse them: the year lives in the header, and one row is a total of the others.
The unit of observation is what one row describes (a country, a country in a year, a household, a sale). The key, as in Part A, is the minimal set of columns that identifies each row: it has no duplicates. The key tells you the structure of the data:
| Structure | One row is | Key | Example |
|---|---|---|---|
| Cross-section | a unit \(i\) at one date | \(i\) | countries in 2023 |
| Time series | a date \(t\) for one unit | \(t\) | Spain, 2000 to 2023 |
| Panel | a unit \(i\) at a date \(t\) | \((i, t)\) | countries, 2000 to 2023 |
Why it matters: every number you compute is “per row”. A mean over rows is a mean over countries, over country-years or over people, depending on what a row is. If the key has duplicates, sums and counts are wrong and nothing warns you.
Rule, in any language: before computing anything, state the unit of observation and check the key.
Application
Question. What does one row of the WDI file describe?
Shape of the answer: a sentence, and a check that returns False (no duplicates).
wdi.shape # (rows, columns)wdi.head()wdi.duplicated(subset=["iso3", "year"]).any() # is any (iso3, year) repeated?wdi["iso3"].nunique(), wdi["year"].nunique()One row is a country in a year: a panel. The key is the pair (iso3, year), with no duplicates. There are 266 codes and 24 years, and 266 × 24 = 6,384 rows: every code has a row for every year (a balanced panel). Limit: a row for every year does not mean a value in every cell, as we will see.
The same in R
# base R
dim(wdi) # rows, columns
anyDuplicated(wdi[, c("iso3", "year")]) # 0: no duplicates
# tidyverse
wdi |> count(iso3, year) |> filter(n > 1) # 0 rows: no duplicates
n_distinct(wdi$iso3)
n_distinct(wdi$year)Stata: isid iso3 year.
In SQL (Part A): SELECT iso3, year, COUNT(*) FROM wdi GROUP BY iso3, year HAVING COUNT(*) > 1.
4. Types of variables
Concept
The type of a variable decides which operations make sense. Three questions about every column:
- How is it stored? Number, text, date, true/false. A numeric column stored as text usually hides a stray entry such as
".."or"n.a.". - What is its role? Identifier (who and when), category (a group) or measure (a quantity).
- For a measure, what kind of quantity?
- a stock: a level at a date (population, debt);
- a flow: an amount over a period (GDP, exports);
- a rate or ratio: one quantity divided by another (unemployment rate, GDP per capita, inflation).
Rule: stocks and flows can be added across units (the population of a region is the sum of its countries). Rates and ratios cannot: the unemployment rate of a region is some average of the rates of its countries, and you must choose the weights (§10). The course’s Data conventions sheet covers this in Units of measurement and Prices.
Application
Question. Which columns of the file can be added across countries?
Shape of the answer: a list of columns.
wdi.info()Read three things: rows, types and missing values (Non-Null Count against the 6,384 rows).
| Column | Meaning (WDI code) | Role | Kind |
|---|---|---|---|
iso3, country |
ISO 3166 alpha-3 code and name | identifier | |
year |
2000 to 2023 | identifier | |
region, income_group |
World Bank classification (the current one, repeated in every year) | category | |
population |
Total population (SP.POP.TOTL) |
measure | stock |
gdp_pc_ppp |
GDP per capita, PPP, constant international $ (NY.GDP.PCAP.PP.KD) |
measure | ratio (flow per person) |
unemployment |
Unemployed, % of the labour force, ILO modelled estimate (SL.UEM.TOTL.ZS) |
measure | rate |
inflation |
Consumer prices, annual % change (FP.CPI.TOTL.ZG) |
measure | growth rate |
life_exp |
Life expectancy at birth, years (SP.DYN.LE00.IN) |
measure | summary of a distribution |
trade_gdp |
Exports plus imports, % of GDP (NE.TRD.GNFS.ZS) |
measure | ratio |
Only population can be added across countries. Every other measure is a rate or a ratio. Limit: the storage type (float64) is the same for all of them, so the software will add unemployment rates without complaint. Only you know the kind of quantity.
The same in R
str(wdi_df) # base R
glimpse(wdi) # tidyverseStata: describe and codebook.
Basic operations on one table
Almost everything you do with one table is a combination of six operations. You know several from the SQL of Part A.
| Operation | What it does | Rows of the result |
|---|---|---|
| Select columns | keeps some variables | the same |
| Filter rows | keeps the observations that meet a condition | fewer |
| Create variables | adds a column computed from others | the same |
| Sort | changes the order of the rows | the same |
| Summarise | reduces many rows to one number | one |
| Group | applies a summary within each group | one per group |
Each operation takes a table and returns a table, so they can be chained. Combining two tables (joins) comes later in the course.
5. Select columns and filter rows
Concept
Selecting keeps some columns: the variables your question needs. Filtering keeps the rows that meet a condition: a statement that is true or false for each row (year == 2023, unemployment > 15). Conditions combine with and, or and not.
The unit of observation stays the same; the table gets smaller.
Filtering is how you define the sample: which countries, which years, which people. Every later number refers to that sample, so the filter is an analytical decision and belongs in the conclusion (“among countries with data in 2023, …”).
Rule: write the condition in words first, and count the rows before and after.
A trap: what does a condition do with a missing value? In pandas NaN > 15 is False, so the row is dropped. In SQL and in dplyr the comparison is missing (NULL, NA) and the row is dropped too. Base R with df[cond, ] returns one row full of NA for each of them; which(cond) and subset() drop them. In Stata a missing value is larger than any number, so unemployment > 15 is true for the missing ones: write unemployment > 15 & !missing(unemployment), or unemployment > 15 & unemployment < ..
Application 1
Question. Which countries had unemployment above 15% in 2023, and in which regions are they?
Shape of the answer: a table, one row per country, three columns; then a count by region.
is_2023 = wdi["year"] == 2023 # one True/False per row
high_u = wdi["unemployment"] > 15
is_2023.sum(), high_u.sum(), (is_2023 & high_u).sum() # rows that meet each condition, and bothwdi.loc[is_2023 & high_u, ["country", "region", "unemployment"]] # .loc[rows, columns]Where are they? The 15 rows are easier to read counted by region. .value_counts() counts how many rows take each value of a column, from the most to the least frequent: a first summary of a category. The same count in R is table(x) or count(df, x), in Stata tabulate x, and in SQL GROUP BY x with COUNT(*).
wdi.loc[is_2023 & high_u, "region"].value_counts() # how many of the 15 in each regionno_value = wdi["unemployment"].isna()
low_u = wdi["unemployment"] <= 15
(is_2023 & no_value).sum(), (is_2023 & ~high_u).sum(), (is_2023 & low_u).sum() # missing; not above 15; at most 15- A comparison returns one
True/Falseper row (a boolean mask). Combine masks with&(and),|(or),~(not), each condition in parentheses if written inline. df.loc[rows, columns]selects by label or by mask;df.iloc[rows, columns]selects by position (wdi.iloc[0:3, 0:2]).df[mask]filters rows;df[["a", "b"]]selects columns.- Other useful conditions:
.isin([...]),.between(a, b),.isna(),.notna(). .value_counts()counts the rows of each value of a column.- The negation and missing values:
~(x > 15)is true for a missingx;x <= 15is false. Of the 266 rows of 2023, 251 are “not above 15” and 217 are “at most 15”: the difference is the 34 rows without a value. In SQL,NOT (x > 15)drops the missing ones, asx <= 15does.
Conclusion: 15 countries had unemployment above 15% in 2023, most of them in Sub-Saharan Africa (8) and in the Middle East and North Africa (6). Limit: these are ILO modelled estimates, and 34 of the 266 rows of 2023 have no value.
The same in R
# base R: df[rows, columns]
cond <- wdi$year == 2023 & wdi$unemployment > 15
table(cond, useNA = "ifany") # FALSE, TRUE and missing (NA)
nrow(wdi[cond, ]) # 49: the 15 rows, and one row of NA for each missing condition
nrow(wdi[which(cond), ]) # 15
wdi[which(cond), c("country", "region", "unemployment")]
subset(wdi, year == 2023 & unemployment > 15, select = c(country, region, unemployment))
# tidyverse
high <- wdi |>
filter(year == 2023, unemployment > 15) |>
select(country, region, unemployment)
high
count(high, region, sort = TRUE) # how many of the 15 in each regionWithout which(), base R returns one row of NA for every row where the condition is missing: 49 rows in place of 15. Stata: list country region unemployment if year == 2023 & unemployment > 15 & !missing(unemployment).
The same in SQL, from Python. DuckDB is a database that runs inside Python or R, with no server. It queries data that are already on your computer (a pandas DataFrame, a CSV or Parquet file) without loading them into a database first: duckdb.sql() finds wdi by its name. It is the SQL of Part A on the tables of Part B.
A database on a server, like the MariaDB of Part A, is reached through a connection: in Python with sqlalchemy and a driver such as pymysql (both in the course environment), then pd.read_sql(); in R with the packages DBI and RMariaDB. DuckDB can also attach a MySQL or PostgreSQL server through its extensions (ATTACH ... (TYPE mysql)).
import duckdb
duckdb.sql("""
SELECT country, region, unemployment
FROM wdi
WHERE year = 2023 AND unemployment > 15
""")high_sql = duckdb.sql("""
SELECT country, region, unemployment
FROM wdi
WHERE year = 2023 AND unemployment > 15
""").df() # .df(): the result as a pandas DataFrame
high_pd = wdi.loc[is_2023 & high_u, ["country", "region", "unemployment"]]
high_sql.equals(high_pd.reset_index(drop=True)) # the same tableEvery SQL line of this notebook runs this way. WHERE unemployment > 15 drops the rows where unemployment is NULL, as the pandas mask does.
Application 2
Question. How many countries does the file have?
Shape of the answer: one number. The United Nations has 193 member states.
wdi["country"].nunique()no_region = wdi["region"].isna()
wdi.loc[no_region, "country"].unique()[:12]266 names is far more than 193. The file mixes countries with aggregates (World, Euro area, High income, …): the Euro area row of table (B) in §3. A tidy table has observations of one kind only. Any sum or average “across countries” that includes the aggregates counts some countries several times.
The aggregates have no region, and that gives the condition to separate them.
countries = wdi[wdi["region"].notna()].copy()
aggregates = wdi[wdi["region"].isna()].copy()
countries["iso3"].nunique(), aggregates["iso3"].nunique()Conclusion: the file has 217 countries and territories and 49 aggregates. From here on the sample is countries. Limit: 217 is still more than 193, because the World Bank lists territories such as Greenland, Gibraltar or Macao as separate economies.
.copy() makes clear that countries is a new table: the columns we add next go to it and leave wdi as it was. This mix of units and totals is the most common trap of World Bank, Eurostat and OECD files.
The same in R
# base R
length(unique(wdi$country))
countries <- wdi[!is.na(wdi$region), ]
aggregates <- wdi[is.na(wdi$region), ]
# tidyverse
n_distinct(wdi$country)
countries <- wdi |> filter(!is.na(region))
aggregates <- wdi |> filter(is.na(region))
n_distinct(countries$iso3)
n_distinct(aggregates$iso3)Stata: keep if !missing(region).
In SQL (Part A): WHERE region IS NOT NULL.
6. Create variables
Concept
A new variable is a function of other columns, computed row by row: each row gets its own result, from its own values. The number of rows stays the same.
Four transformations cover most of applied economics:
- total ↔︎ per capita (multiply or divide by population), and shares;
- logs: they turn ratios into differences (a gap of 0.69 in logs is a factor of 2), which is why income is almost always analysed in logs;
- dummies: a condition turned into a 0/1 variable;
- growth rates, which need the previous period of the same unit (later in the course).
Rule: a new column has the unit of observation of its table, and you should be able to say its units aloud (billions of PPP dollars, log points, 0/1). A missing input gives a missing result in arithmetic. In a comparison it depends on the language: pandas gives False (a 0 in the dummy), Stata gives true (a 1) and R gives NA. Build a dummy only where the input has a value.
Application
Question. The file has GDP per capita. How large is each economy?
Shape of the answer: the same rows, one more column. Total GDP = GDP per capita × population.
countries["gdp_bn"] = countries["gdp_pc_ppp"] * countries["population"] / 1e9 # billions of PPP $
countries["log_gdp_pc"] = np.log(countries["gdp_pc_ppp"])
countries["high_income"] = (countries["income_group"] == "High income").astype(int)
c23 = countries[countries["year"] == 2023] # the cross-section of 2023
five = c23["iso3"].isin(["CHN", "IND", "USA", "ESP", "LUX"])
c23.loc[five, ["country", "population", "gdp_pc_ppp", "gdp_bn", "log_gdp_pc", "high_income"]].round(2)- An operation between columns is computed row by row, without loops.
- A comparison gives
True/False;.astype(int)turns it into a 0/1 dummy. c23is a filter ofcountriesmade after creating the columns, so it has them.
The dummy and missing values: high_income comes from a column without gaps. With unemployment, which has them:
c23["unemployment"].isna().sum(), (c23["unemployment"] > 15).astype(int).value_counts().to_dict()The 33 countries without a value get a 0, as if their unemployment were low: 202 zeros and 15 ones. R keeps them missing (169 zeros, 15 ones, 33 NA) and Stata gives them a 1. A dummy that should be missing where the input is missing has to say so: (x > 15).astype(int).where(x.notna()) in pandas.
Conclusion: size and income per person are different things. China is the largest of the five economies (32,005 billion PPP dollars) with less than a third of the GDP per capita of the United States; Luxembourg has the highest GDP per capita and an economy of 87 billion. Limit: PPP dollars compare volumes of goods and services; at market exchange rates the United States is the larger economy.
The same in R
# base R
countries$gdp_bn <- countries$gdp_pc_ppp * countries$population / 1e9
countries$log_gdp_pc <- log(countries$gdp_pc_ppp)
countries$high_income <- as.integer(countries$income_group == "High income")
# tidyverse
countries <- countries |>
mutate(gdp_bn = gdp_pc_ppp * population / 1e9, # billions of PPP $
log_gdp_pc = log(gdp_pc_ppp),
high_income = as.integer(income_group == "High income"))
c23 <- countries |> filter(year == 2023) # the cross-section of 2023
c23 |>
filter(iso3 %in% c("CHN", "IND", "USA", "ESP", "LUX")) |>
select(country, population, gdp_pc_ppp, gdp_bn, log_gdp_pc, high_income)
# a dummy from a condition with missing values: R keeps them missing
table(as.integer(c23$unemployment > 15), useNA = "ifany")Stata: gen gdp_bn = gdp_pc_ppp * population / 1e9, and for the dummy gen high_u = unemployment > 15 if !missing(unemployment) (without the if, the 33 missing ones get a 1).
In SQL (Part A): SELECT gdp_pc_ppp * population / 1e9 AS gdp_bn.
7. Sort
Concept
Sorting changes the order of the rows by the values of one or more variables. The content of the table stays the same.
You sort for three reasons:
- a ranking: the top or the bottom n (sort, then keep the first rows);
- looking at the extremes of a variable, where errors and the most interesting cases live;
- putting a unit’s rows in time order, which lags and growth rates need.
Rule: say which variable defines “first” before sorting: the largest and the richest are different rankings. Missing values go to the end.
Operations are chained: filter, then sort, then select, then keep the first rows. pandas chains methods with ., R with the pipe |>, SQL in one statement.
Application 1
Question. Which are the largest economies in 2023? Is it the same list as the richest?
Shape of the answer: two tables of 8 rows.
(c23.sort_values("gdp_bn", ascending=False)
[["country", "gdp_bn", "gdp_pc_ppp"]]
.head(8)
.round(0))(c23.sort_values("gdp_pc_ppp", ascending=False)
[["country", "gdp_bn", "gdp_pc_ppp"]]
.head(8)
.round(0))Conclusion: two questions, two lists with no country in common. The size of an economy (market, weight in trade, power) and income per person rank countries differently.
Limit: GDP per capita counts what is produced in the territory. In Singapore, Luxembourg, Ireland, Qatar, Macao and Bermuda a large part goes to multinational profits, cross-border workers or foreign owners, so gross national income (GNI) per capita measures the living standard of residents better.
The same in R
# base R
top <- c23[order(-c23$gdp_bn), c("country", "gdp_bn", "gdp_pc_ppp")]
head(top, 8)
# tidyverse
c23 |>
arrange(desc(gdp_bn)) |>
select(country, gdp_bn, gdp_pc_ppp) |>
head(8)Stata: gsort -gdp_bn and list country gdp_bn gdp_pc_ppp in 1/8.
In SQL (Part A): ORDER BY gdp_bn DESC LIMIT 8.
Application 2 (if time; otherwise at home)
Question. The ten highest inflation rates in the panel. Are they errors in the data?
Shape of the answer: 10 rows (country, year, inflation).
countries.sort_values("inflation", ascending=False)[["country", "year", "inflation"]].head(10).round(0)Inflation of several hundred per cent looks like an error, but these are well documented episodes (Zimbabwe, Sudan, Venezuela, Lebanon). Before dropping an extreme value, check whether it is impossible (a negative population, an unemployment rate above 100) or only unusual. Unusual values are often the most informative ones.
Now look at what is absent from the list: Zimbabwe’s hyperinflation of 2008, the largest of the period.
zwe = (countries["iso3"] == "ZWE") & countries["year"].between(2005, 2010)
countries.loc[zwe, ["country", "year", "inflation"]]Conclusion: the ten highest rates are facts. Limit: the list is incomplete in a systematic way. Zimbabwe has no value from 2005 to 2009 and Venezuela none from 2017 to 2023: the data are missing when inflation was most extreme.
8. Summarise
Concept
A summary reduces many rows to one number: a count, a sum, a mean, a median, a minimum or a maximum.
The unit of observation changes: from a country to “the set of countries in the sample”. That is the price of a summary, and the reason to choose it with care:
- mean or median? Income, firm size and wealth have a long right tail: a few very large values pull the mean up. The median describes the typical unit; the mean is what you need for totals.
- over which rows? The summary describes the rows that have a value. Summary functions skip missing values in silence in pandas, Stata and SQL. R returns
NAuntil you writena.rm = TRUE.
Rule: next to every mean or median, report how many observations it is based on.
Application
Question. What is the GDP per capita of the typical country in 2023?
Shape of the answer: one number, and the count behind it.
c23[["gdp_pc_ppp", "unemployment", "inflation", "life_exp"]].describe().round(1)c23["gdp_pc_ppp"].agg(["size", "count", "mean", "median"]).round(0) # size: rows; count: rows with a valueRead it: count (how many of the 217 countries have the variable?), mean against median (50%), minimum and maximum.
Conclusion: the typical country had a GDP per capita of about 17,700 PPP dollars in 2023 (the median). The mean, 27,400, is more than 50% higher because of a few very rich economies. Limit: the figure describes the 197 countries with data; 20 have none.
The same in R
# base R
summary(c23$gdp_pc_ppp) # the last figure counts the missing values
mean(c23$gdp_pc_ppp) # NA: there are missing values
mean(c23$gdp_pc_ppp, na.rm = TRUE)
# tidyverse
c23 |>
summarise(n = n(),
n_gdp = sum(!is.na(gdp_pc_ppp)),
mean = mean(gdp_pc_ppp, na.rm = TRUE),
median = median(gdp_pc_ppp, na.rm = TRUE))Stata: summarize gdp_pc_ppp, detail.
In SQL (Part A): SELECT COUNT(*), COUNT(gdp_pc_ppp), AVG(gdp_pc_ppp) FROM c23 (COUNT(*) counts rows; COUNT(column) skips the missing ones).
9. Group, and who is missing
Concept
Grouping applies a summary within each group: split the rows by the values of a variable, summarise each part, and put the results together. The result has one row per group, and the group becomes the unit of observation.
It is the operation behind every table “by region”, “by sector”, “by year”. The rule of §8 holds within each group: a median of 5 countries and a median of 50 are not equally informative.
Counting by group is also how you find out who is missing. Missing data have a reason, and the reason decides what you may do:
- Missing completely at random (MCAR): the gap has nothing to do with the unit. Dropping the rows only costs precision.
- Missing at random (MAR): the gap depends on things you observe (size, region). You can correct for it with those variables.
- Missing not at random (MNAR): the gap depends on the missing value itself, like the inflation of Zimbabwe and Venezuela, missing when it was highest (Application 2 of §7). Nothing in the data fixes it; you state it as a limit.
Rule: count, explain, then decide, and write the decision down.
Application 1
Question. How does income vary across regions in 2023, and how many countries is each figure based on?
Shape of the answer: one row per region (7 rows), with two counts and a median.
(c23.groupby("region")
.agg(n_countries=("iso3", "size"), # all rows of the group
n_with_gdp=("gdp_pc_ppp", "count"), # rows with a value
gdp_pc_median=("gdp_pc_ppp", "median"))
.sort_values("gdp_pc_median")
.round(0))Conclusion: the median country of Sub-Saharan Africa has a GDP per capita of about 3,600 PPP dollars, against 41,300 in Europe and Central Asia: a factor of 11. Limit: the figure for North America rests on 3 economies and the one for South Asia on 6, and East Asia and Pacific lacks data for 6 of its 37.
The same in R
# base R (the formula drops the rows with missing values)
aggregate(gdp_pc_ppp ~ region, data = c23, FUN = median)
# tidyverse
c23 |>
group_by(region) |>
summarise(n_countries = n(), # all rows: COUNT(*) in SQL; count() gives the same
n_with_gdp = sum(!is.na(gdp_pc_ppp)), # rows with a value: COUNT(gdp_pc_ppp) in SQL
gdp_pc_median = median(gdp_pc_ppp, na.rm = TRUE)) |>
arrange(gdp_pc_median)Stata: collapse (count) n_with_gdp = gdp_pc_ppp (median) gdp_pc_median = gdp_pc_ppp, by(region).
The same in SQL, on the DataFrame c23: COUNT(*) counts rows and COUNT(column) the rows with a value, as size and count do in pandas.
duckdb.sql("""
SELECT region, COUNT(*) AS n_countries, COUNT(gdp_pc_ppp) AS n_with_gdp, MEDIAN(gdp_pc_ppp) AS gdp_pc_median
FROM c23
GROUP BY region
ORDER BY gdp_pc_median
""")The same three columns as the pandas table. DuckDB has MEDIAN; MySQL has none, and there you would report AVG(gdp_pc_ppp).
Application 2 (if time; otherwise at home)
Question. Which countries never report an unemployment rate? Are they a random subset?
Shape of the answer: a list of country names. The tool: group by country and count the years with a value.
years_with_u = countries.groupby("country")["unemployment"].count() # one row per country
never = years_with_u[years_with_u == 0]
len(never), never.index.tolist()Conclusion: 30 of the 217 never report unemployment. They are small territories and microstates, plus Kosovo (1.7 million people, outside the ILO estimates): far from a random sample of the world. The gap is MAR: it depends on size, which we observe. Limit of any “world” unemployment figure computed from this file: it describes the countries with data.
The same in R
# base R
years_with_u <- tapply(!is.na(countries$unemployment), countries$country, sum)
names(years_with_u[years_with_u == 0])
# tidyverse
never <- countries |>
group_by(country) |>
summarise(years_with_u = sum(!is.na(unemployment))) |>
filter(years_with_u == 0)
nrow(never)Stata: egen years_with_u = count(unemployment), by(country).
10. Averages and weights
Concept
An average of a rate or a ratio needs weights, and the weights decide whose average it is. For “the GDP per capita of a region” there are two candidates:
- mean of ratios: average the GDP per capita of the countries. Every country weighs the same: the average country.
- ratio of sums: total GDP of the region divided by total population. Every person weighs the same: the average person.
The ratio of sums is a weighted mean of the country ratios, with population as the weight:
\[\frac{\sum_i \text{GDP}_i}{\sum_i \text{pop}_i} = \sum_i w_i \, \frac{\text{GDP}_i}{\text{pop}_i}, \qquad w_i = \frac{\text{pop}_i}{\sum_j \text{pop}_j}\]
Both are valid, and they answer different questions. The same choice appears with firms (the average firm or the average worker), households and regions.
Rule: for every average of a ratio, say what the weights are. An unweighted mean has weights too: they are equal.
Application
Question. What is “the GDP per capita of Sub-Saharan Africa”?
Shape of the answer: 7 rows (regions), 2 columns (the two averages).
ok = c23.dropna(subset=["gdp_pc_ppp", "population"]) # the same countries in both
reg = ok.groupby("region").agg(mean_of_ratios=("gdp_pc_ppp", "mean"),
gdp=("gdp_bn", "sum"),
pop=("population", "sum"))
reg["ratio_of_sums"] = reg["gdp"] * 1e9 / reg["pop"]
reg[["mean_of_ratios", "ratio_of_sums"]].round(0)The two answers differ, and in the same direction in every region. Small rich countries and territories pull the simple average up; the populous countries, which weigh more in the ratio of sums, are poorer. In the Middle East and North Africa the average country has twice the income of the average person.
Check against the source (if time; otherwise at home). The World Bank builds its regional aggregates as a ratio of sums. They are in the file (the rows we set aside in §5). Does our figure reproduce them?
The index of §2 does the work here: set_index("iso3") makes the code the row label, and .map() then looks up each region’s code in that index.
agg_codes = {"East Asia & Pacific": "EAS", "Europe & Central Asia": "ECS",
"Latin America & Caribbean": "LCN", "Middle East & North Africa": "MEA",
"North America": "NAC", "South Asia": "SAS", "Sub-Saharan Africa": "SSF"}
official = aggregates[aggregates["year"] == 2023].set_index("iso3")["gdp_pc_ppp"] # a Series indexed by code
reg["official"] = reg.index.map(agg_codes).map(official)
reg[["ratio_of_sums", "official"]].round(0)Identical in North America and South Asia, close elsewhere, and furthest in Middle East & North Africa (in the World Bank’s classification this region includes Afghanistan and Pakistan: 23 economies). The World Bank fills the gaps of countries with missing data before adding up; we dropped them. Which ones?
mena = c23[c23["region"] == "Middle East & North Africa"]
mena.loc[mena["gdp_pc_ppp"].isna(), ["country", "population"]]Conclusion: the GDP per capita of Sub-Saharan Africa is about 4,800 PPP dollars for the average person and 6,200 for the average country, and the first figure is the one the World Bank publishes. Limit: who is missing changes the answer. Two poor and populous countries without data (63 million people) put our figure for the Middle East and North Africa above the official one.
The same in R
# base R: weighted.mean(x, w)
ok <- c23[!is.na(c23$gdp_pc_ppp) & !is.na(c23$population), ]
sapply(split(ok, ok$region), function(d) weighted.mean(d$gdp_pc_ppp, d$population))
# tidyverse
reg <- c23 |>
filter(!is.na(gdp_pc_ppp), !is.na(population)) |>
group_by(region) |>
summarise(mean_of_ratios = mean(gdp_pc_ppp),
ratio_of_sums = sum(gdp_pc_ppp * population) / sum(population))
regStata: collapse (mean) gdp_pc_ppp [aweight = population], by(region).
In SQL (Part A): SELECT region, AVG(gdp_pc_ppp), SUM(gdp_pc_ppp * population) / SUM(population) FROM ok GROUP BY region.
11. Describe, predict, explain
In class: the concept and the table. The R block is for home.
Concept
A table of data can serve three purposes, and each needs different evidence:
- describe: what the data look like (levels, differences between groups, trends);
- predict: guess the value of one variable from others, for a unit you have not seen;
- explain: say what would happen to one variable if you changed another (a causal effect).
A good description supports a rough prediction. Neither supports an explanation: two variables can move together because a third one drives both, or because the effect runs the other way.
Rule: say which of the three your sentence claims. Most of this course is about the first two.
Application
Question. Do people in richer countries live longer?
Shape of the answer: 4 rows, one per income quartile. pd.qcut(x, 4) creates a category from a numeric variable: four groups with the same number of countries.
c23 = c23.assign(income_bracket=pd.qcut(c23["gdp_pc_ppp"], 4,
labels=["Q1 poorest", "Q2", "Q3", "Q4 richest"]))
c23.groupby("income_bracket", observed=True)["life_exp"].agg(["count", "median", "min", "max"]).round(1)Conclusion: the table describes: median life expectancy rises by 16 years from the poorest to the richest quartile. It lets you predict, with a wide margin: the ranges overlap (the poorest quartile reaches 72.9, the richest starts at 70.2). Limit: it does not explain. It cannot tell whether income buys health, or whether health, education and institutions raise both.
The same in R
# base R: cut() with the quartiles as breaks
breaks <- quantile(c23$gdp_pc_ppp, 0:4 / 4, na.rm = TRUE)
c23$income_bracket <- cut(c23$gdp_pc_ppp, breaks, include.lowest = TRUE,
labels = c("Q1 poorest", "Q2", "Q3", "Q4 richest"))
# tidyverse (uses the column created above)
c23 |>
filter(!is.na(income_bracket)) |>
group_by(income_bracket) |>
summarise(count = n(), median = median(life_exp), min = min(life_exp), max = max(life_exp))Stata: xtile income_bracket = gdp_pc_ppp, nq(4) and tabstat life_exp, by(income_bracket) stat(n median min max).
12. Exercise
In class: 12.1, and 12.2 if there is time. At home: the rest.
Work in pairs. Before writing code, tell your partner the unit of observation and what the result should look like (one number? a table with how many rows?). Finish each one with a sentence and its limit. Use pandas here or R in S01_R.ipynb: one language is enough.
12.1 (in class) How many countries have a value of gdp_pc_ppp in 2000, and how many in 2023? Which countries are in one year and absent from the other, and why might that be? Use countries.
# your code here12.2 (if time; otherwise at home) Spain against the euro area: the unemployment rate from 2007 to 2014. The euro area is an aggregate (iso3 equal to EMU), so start from wdi. Build a table with the columns country, year and unemployment, sorted by year. Read the gap between the two in 2007 and in 2013 and write one sentence: was Spain’s crisis exceptional?
# your code here12.3 (at home) The ten countries with the highest unemployment in 2023, with their region and income group. What do they have in common?
# your code here12.4 (at home) Life expectancy in 2019 in high-income countries and in the rest: the average country and the average person. Which one would a health ministry use, and which one a demographer comparing health systems?
# your code here13. The same operations in every language
| Operation | pandas | base R | dplyr (tidyverse) | Stata | SQL (Part A) |
|---|---|---|---|---|---|
| Read a CSV file | pd.read_csv("f.csv") |
read.csv("f.csv") |
read_csv("f.csv") |
import delimited "f.csv" |
(table in the database) |
| Rows, columns, types | df.shape, df.info() |
dim(df), str(df) |
glimpse(df) |
describe |
DESCRIBE t |
| Unique key | df.duplicated(["i", "t"]).any() |
anyDuplicated(df[, c("i", "t")]) |
count(df, i, t) with n > 1 |
isid i t |
GROUP BY i, t HAVING COUNT(*) > 1 |
| Select columns | df[["a", "b"]] |
df[, c("a", "b")] |
select(df, a, b) |
keep a b |
SELECT a, b |
| Filter rows | df[df.x > 1], df.loc[mask, cols] |
df[which(df$x > 1), ], subset() |
filter(df, x > 1) |
keep if x > 1 & !missing(x) |
WHERE x > 1 |
| Dummy from a condition | (df.x > 1).astype(int) |
as.integer(df$x > 1) |
mutate(d = as.integer(x > 1)) |
gen d = x > 1 if !missing(x) |
CASE WHEN x > 1 THEN 1 ELSE 0 END |
| Count by category | df.g.value_counts() |
table(df$g) |
count(df, g) |
tabulate g |
SELECT g, COUNT(*) ... GROUP BY g |
| Missing values | df.x.isna() |
is.na(df$x) |
is.na(x) |
missing(x) |
x IS NULL |
| Create a variable | df["z"] = df.x * df.y, assign() |
df$z <- df$x * df$y |
mutate(df, z = x * y) |
gen z = x * y |
SELECT x * y AS z |
| Sort | df.sort_values("x", ascending=False) |
df[order(-df$x), ] |
arrange(df, desc(x)) |
gsort -x |
ORDER BY x DESC |
| First rows | df.head(8) |
head(df, 8) |
head(df, 8), slice_max() |
list in 1/8 |
LIMIT 8 |
| Summarise | df.x.mean(), df.describe() |
mean(df$x, na.rm = TRUE), summary(df) |
summarise(df, m = mean(x, na.rm = TRUE)) |
summarize x, detail |
SELECT AVG(x) |
| Count rows and values | ("x", "size"), ("x", "count") |
nrow(df), sum(!is.na(df$x)) |
n(), sum(!is.na(x)) |
count, count if !missing(x) |
COUNT(*), COUNT(x) |
| Summarise by group | df.groupby("g").agg(m=("x", "mean")) |
aggregate(x ~ g, data = df, FUN = mean) |
group_by(df, g) \|> summarise(m = mean(x)) |
collapse (mean) x, by(g) |
SELECT g, AVG(x) ... GROUP BY g |
| Weighted mean | (x * w).sum() / w.sum() |
weighted.mean(x, w) |
weighted.mean(x, w) |
[aweight = w] |
SUM(x * w) / SUM(w) |
| Chain operations | methods with . |
nested calls, \|> |
\|> or %>% |
one command per line | one statement |
Combining tables (joins) and changing the shape of a table (long and wide) come later in the course. In the tests you may answer in pandas, in R (base or dplyr) or in Stata.
Before you leave: Kernel → Restart Kernel and Run All Cells. If it runs to the end without errors, your notebook is reproducible.
Read: QuantEcon, Python Programming for Economics and Finance, lecture Pandas (python-programming.quantecon.org). For R: Wickham, Çetinkaya-Rundel and Grolemund, R for Data Science, 2nd ed., chapters Data transformation and Data tidying (r4ds.hadley.nz). Secondary: McKinney, Python for Data Analysis, 3rd ed., ch. 5 and 10.