本书暂未推出简体中文版。现有版本:English。
University Economics — Year 1 · 本科一年级
28Economic Data with Python
Three analysts are asked how fast the euro-area economy grew from 2000 to 2023. The first divides GDP in current euros in 2023 by GDP in 2000 and finds a year. The second uses GDP in chained volumes and finds . The third divides by population and finds . All three are right; they answer three different questions, and a report that prints one of them without saying which has made an error that no reader can find. This chapter is about the steps between a published table and a number in a report: loading, joining, converting, adjusting and writing — each done by a script that can be run again.
The unadjusted series swings with the calendar: prices rise faster in the first months of the year and slower at its end. Over the 120 months its standard deviation is points, against for the adjusted series.
Read without adjustment, a fall in December looks like news; it is the season.
You already know
Python, lists, dictionaries, functions, reading a file and first tables were met in the computer science series. Growth rates and logarithms are Chapter 1; price indices, deflators and chained indices are Chapter 7.
28.1 Three shapes of data
Definition 28.1 (Cross-section, time series, panel data)
A cross-section observes many units at one date; a time series observes one unit at many dates; panel data observe many units at many dates.
Definition 28.2 (Unit of observation)
The unit of observation is what one row of a table describes: a country in a year, a household, a firm in a month.
Definition 28.3 (Merge key)
A merge key is the set of columns that identifies a unit of observation, such as (iso3, year): no two rows of a table share it, and two tables are joined by matching it.
A panel can be stored long, one row per unit and date, or wide, one row per unit and one column per date. Long tables are what programs join and filter; wide tables are what people read.
"""A first look at a table: Penn World Table rows for France and Germany."""
from econdata import pwt
d = pwt(["FRA", "DEU"], since=2015, cols=["rgdpe", "pop", "emp"])
print(d.shape) # (rows, columns)
print(d.dtypes)
print(d.head(4))
$ python first_look.py
(18, 6)
iso3 str
country str
year int64
rgdpe float64
pop float64
emp float64
dtype: object
iso3 country year rgdpe pop emp
3469 DEU Germany 2015 4420290.0 82.0776 43.3498
3470 DEU Germany 2016 4579980.0 82.7601 43.9107
3471 DEU Germany 2017 4755890.0 83.1040 44.5363
3472 DEU Germany 2018 4840360.0 83.3685 45.1352
(iso3, year).Three things are worth reading before any computation. The shape says how many rows to expect from every later step. The types say that iso3 and country are text and year an integer, so a year can be compared and sorted. The numbers at the left, 3469 to 3472, are positions in the full table, not years. The output does not give the units: rgdpe is in millions of 2021 dollars and pop and emp in millions of people. They come from the source’s documentation, and any script that divides one column by another must use them.
"""Long and wide: GDP per person of five countries, 2019-2023."""
from econdata import pwt
d = pwt(["BRA", "CHN", "DEU", "IND", "USA"], since=2019, cols=["rgdpe", "pop"])
d["gdppc"] = (d.rgdpe / d["pop"]).round(0) # dollars per person
long = d[["iso3", "year", "gdppc"]]
print("long:", long.shape)
print(long.head(3))
wide = long.pivot(index="iso3", columns="year", values="gdppc")
print("wide:", wide.shape)
print(wide)
back = wide.reset_index().melt(id_vars="iso3", value_name="gdppc")
print("back to long:", back.shape)
pivot and melt. code/bachelor-1/28-economic-data-python/listings/long_and_wide.py$ python long_and_wide.py
long: (25, 3)
iso3 year gdppc
1845 BRA 2019 17063.0
1846 BRA 2020 16620.0
1847 BRA 2021 17671.0
wide: (5, 5)
year 2019 2020 2021 2022 2023
iso3
BRA 17063.0 16620.0 17671.0 18149.0 18805.0
CHN 17770.0 18161.0 19808.0 20485.0 21503.0
DEU 60283.0 58370.0 59758.0 59515.0 59854.0
IND 7390.0 7095.0 7936.0 8315.0 8723.0
USA 68683.0 66808.0 71048.0 72792.0 74654.0
back to long: (25, 3)
pivot takes the key apart: iso3 becomes the rows and year the columns, so each pair may appear only once, or pandas raises an error. melt puts the key back together, with the former column names in a column of their own. The round trip returns the 25 rows it started from, a cheap check that nothing was lost. The wide table is the one to read. Germany’s GDP per person in 2023, 59,854 dollars, was still below its 2019 level of 60,283; seen from the long table, that comparison needs a filter.
28.2 Loading and joining
Two sources rarely cover the same units. A join keeps what matches, and whatever does not match is lost without a message unless one asks for it. The argument indicator=True adds a column that says, for each row, whether its key was found in both tables or in one only.
"""Join two sources on (iso3, year) and count what did not match."""
from econdata import pwt, wdi
w = wdi("NY.GDP.PCAP.PP.KD", since=2019, until=2019) # World Bank
p = pwt(since=2019, until=2019, cols=["rgdpe", "pop"]) # Penn World Table
m = w.merge(p, on=["iso3", "year"], how="outer", indicator=True)
print(m["_merge"].value_counts())
left = m[m["_merge"] == "left_only"]
print("only in the World Bank table:", sorted(left.iso3)[:8])
right = m[m["_merge"] == "right_only"]
print("only in the Penn table:", sorted(right.iso3))
$ python join_sources.py
_merge
both 178
left_only 69
right_only 7
Name: count, dtype: int64
only in the World Bank table: ['AFE', 'AFG', 'AFW', 'AND', 'ARB', 'CEB', 'CSS', 'EAP']
only in the Penn table: ['AIA', 'MSR', 'SSD', 'TWN', 'VEN', 'VGB', 'YEM']
The first keys found only in the World Bank table show what most of them are. AFE and AFW are the two halves of sub-Saharan Africa, ARB is the Arab world and CEB is central Europe and the Baltics: aggregates, not countries. AFG and AND are countries that the Penn table does not cover. The seven keys found only in the Penn table — Anguilla, Montserrat, the British Virgin Islands, Taiwan, South Sudan, Venezuela and Yemen — have no value in this World Bank series. An inner join would have dropped all 76 keys without a word.
The commonest silent error is the opposite one: a key that is too short. Merging two panels on the country alone, forgetting the year, pairs every year of one table with every year of the other.
"""A merge on too few keys multiplies rows without any error."""
from econdata import pwt, wdi
w = wdi("NY.GDP.PCAP.PP.KD", since=2015, until=2019, countries_only=True)
p = pwt(since=2015, until=2019, cols=["rgdpe", "pop"])
print("rows:", len(w), len(p))
bad = w.merge(p, on="iso3") # forgot the year
print("merged on iso3 alone:", len(bad))
good = w.merge(p, on=["iso3", "year"], validate="one_to_one")
print("merged on (iso3, year):", len(good))
$ python join_trap.py
rows: 995 925
merged on iso3 alone: 4450
merged on (iso3, year): 890
The arithmetic shows what happened. Over the five years the World Bank table has 199 economies and the Penn table 185, and 178 are in both. On the right key the merge keeps the 890 country-years found in both. On the country alone, each of those country-years is paired with all five years of the other table: rows, every one of which looks like valid data.
The argument validate="one_to_one" makes pandas raise an error if a key appears twice on either side. It costs one line and turns a silent error into a loud one.
28.3 Units and frequencies
A series is a level (GDP in euros), a ratio (GDP per person, a debt ratio) or a rate (inflation). Turning monthly data into yearly data depends on what the series measures: a flow (spending in a month) is summed; a price or a rate is averaged; a stock (debt at the end of a month) takes the last value.
"""From monthly to yearly: the average, the end of the year, the published average."""
from cpi_tools import monthly
from econdata import bls_cpi
cpi = monthly("CUUR0000SA0", since=2020, until=2024)
by_year = cpi.groupby(level="year")
out = by_year.mean().round(3).to_frame("average")
out["december"] = by_year.last()
d = bls_cpi("CUUR0000SA0")
published = d[d.period == "M13"].set_index("year").value # BLS annual average
out["published"] = published.loc[2020:2024]
print(out)
$ python monthly_to_yearly.py
average december published
year
2020 258.811 260.474 258.811
2021 270.970 278.802 270.970
2022 292.655 296.797 292.655
2023 304.702 306.746 304.702
2024 313.689 315.605 313.689
The published annual figure is the average of the twelve months, and the listing finds it again to the third decimal. In these years of rising prices the December value is above the average every year, by 1.7 points in 2020 and 4.1 in 2022. A report that compares one year’s December with another year’s average mixes two measures.
The helper monthly that these listings import drops the row the statistical office uses for the annual average (period M13) and indexes the rest by (year, month).
"""Monthly CPI series as a pandas Series indexed by (year, month)."""
import warnings
import pandas as pd
from econdata import bls_cpi
# the loader's file has a column of mixed types that we never use
warnings.filterwarnings("ignore", category=pd.errors.DtypeWarning)
def monthly(series_id="CUUR0000SA0", since=2014, until=2025):
d = bls_cpi(series_id)
d = d[
d.period.str.match(r"M(0[1-9]|1[0-2])")
].copy() # drop M13, the annual average
d["month"] = d.period.str[1:].astype(int)
d = d[(d.year >= since) & (d.year <= until)]
return d.sort_values(["year", "month"]).set_index(["year", "month"]).value
This file is a module, not a script: it prints nothing, and the other listings import its function, so that every one of them filters the period codes in the same way. The warning it silences concerns a column of the loader’s file that no listing reads.
Definition 28.4 (Annualised rate)
The annualised rate of a change over a period shorter than a year is the change it would give over a year if repeated: for a monthly change , ; for a quarterly change, .
"""Month-on-month, twelve-month and annualised changes of consumer prices."""
from cpi_tools import monthly
for sid, name in [("CUUR0000SA0", "not adjusted"), ("CUSR0000SA0", "adjusted")]:
cpi = monthly(sid)
mom = 100 * (cpi / cpi.shift(1) - 1)
yoy = 100 * (cpi / cpi.shift(12) - 1)
ann = 100 * ((cpi / cpi.shift(1)) ** 12 - 1) # one month's change, compounded
print(f"June 2022, {name}:")
print(f" month on month {mom.loc[(2022, 6)]:6.2f}")
print(f" twelve months {yoy.loc[(2022, 6)]:6.2f}")
print(f" annualised {ann.loc[(2022, 6)]:6.2f}")
$ python changes.py
June 2022, not adjusted:
month on month 1.37
twelve months 9.06
annualised 17.79
June 2022, adjusted:
month on month 1.26
twelve months 8.98
annualised 16.16
The same month gives a rise of , or , depending on the question. An annualised monthly rate is noisy and amplifies the season; a twelve-month change is smooth but six months late on average.
28.4 Seasonal adjustment
Definition 28.5 (Seasonal adjustment, seasonal factor)
A seasonal factor is the typical ratio of a series in a given month (or quarter) to its trend. Seasonal adjustment divides each value by its month’s factor, removing the movements that recur at the same time every year.
The simplest method estimates the trend by a centred twelve-month moving average, with weights on the two ends and on the eleven months between them, so that every calendar month counts equally. The ratio of the series to that trend, averaged month by month and scaled to average 1, gives the factors.
"""Seasonal adjustment by the ratio to a centred moving average."""
import pandas as pd
from cpi_tools import monthly
def adjust(x):
"""x: monthly Series indexed by (year, month). Returns (factors, adjusted)."""
m12 = x.rolling(12).mean()
trend = (m12.shift(-6) + m12.shift(-5)) / 2 # centred: 1/24, 1/12 x 11, 1/24
ratio = (x / trend).dropna()
factors = ratio.groupby(level="month").mean()
factors = factors / factors.mean() # average 1 over the year
months = x.index.get_level_values("month")
return factors, x / factors.loc[months].to_numpy()
if __name__ == "__main__":
nsa = monthly("CUUR0000SA0")
factors, adj = adjust(nsa)
print("seasonal factors by month:")
print(factors.round(4).to_string())
sa = monthly("CUSR0000SA0")
d = pd.DataFrame({"hand": adj.pct_change(), "official": sa.pct_change()})
d = d.loc[2015:2024]
print("months:", len(d))
print("correlation of monthly changes:", round(d.hand.corr(d.official), 3))
$ python seasonal_by_hand.py
seasonal factors by month:
month
1 0.9956
2 0.9979
3 1.0000
4 1.0011
5 1.0025
6 1.0043
7 1.0034
8 1.0021
9 1.0015
10 1.0006
11 0.9972
12 0.9937
months: 120
correlation of monthly changes: 0.975
The factors run from 0.9937 in December to 1.0043 in June, a swing of about one per cent within the year. That is as large as a whole month of the inflation of 2022, which is why the unadjusted series of the opening chart swings. In the function, a twelve-month mean averaged with itself shifted by one month gives the centred trend, with weights at the two ends. The first and last six months have no centred trend and are dropped. The official method fills them with forecasts (measure box below).
The two adjusted series have a correlation of over the 120 months.
The chart’s table is written by a script that imports the listing’s function, so the chart and the listing cannot drift apart.
How it is measured — Seasonal adjustment
The statistical office computes its factors with the X-13ARIMA-SEATS method, which extends the series with forecasts before averaging, so that the most recent months have a centred trend, and treats outliers and calendar effects. Its factors are updated each February, and the previous five years of adjusted data are revised. An adjusted figure is therefore never final: last year’s December will change next February.
28.5 Deflating, indexing, logarithms and growth
A real series divides a nominal one by a price index and multiplies by its base-year value. An index rebased to year divides by its value in and multiplies by 100. The difference of logarithms is a growth rate in log points; their mean over a span is the average log growth, close to the compound rate when growth is small.
"""Brenland's GDP: nominal to real, an index with 2020 = 100, log growth."""
import numpy as np
from country import load
a = load("accounts").set_index("year")
real = a.gdp / a.deflator * 100 # millions of 2015 dalens
index = (100 * real / real.loc[2020]).round(1)
growth = 100 * np.log(real).diff() # log points per year
print(index.loc[[2015, 2020, 2025]].to_string())
print("mean log growth 2016-2025:", round(growth.loc[2016:2025].mean(), 2))
print(
"check against the published real GDP:", round((real - a.real_gdp).abs().max(), 0)
)
$ python deflate_and_index.py
year
2015 97.1
2020 100.0
2025 114.3
mean log growth 2016-2025: 1.63
check against the published real GDP: 0.0
The last line is a check: recomputing a published series and finding no difference is how one learns that the deflator and the base year were the ones assumed. A deflator chained year by year (Chapter 7) makes real components that do not add up to real GDP: a check that adds up real consumption, investment, government purchases and net exports then fails, for a reason that must be stated. The check of the listing cannot fail that way, because real GDP is recomputed from its own deflator.
"""Euro area, 2000-2023: three growth rates from the same accounts."""
from econdata import eurostat, wdi
g = eurostat("nama_10_gdp")
g = g[(g.geo == "EA20") & (g.na_item == "B1GQ")]
g = g.assign(time=g.time.astype(int))
real = g[g.unit == "CLV20_MEUR"].set_index("time").value # chained volumes
nominal = g[g.unit == "CP_MEUR"].set_index("time").value # current prices
pop = wdi("SP.POP.TOTL", isos=["EMU"]).set_index("year").value
def yearly(x, a=2000, b=2023):
return 100 * ((x[b] / x[a]) ** (1 / (b - a)) - 1)
print(f"GDP, current prices {yearly(nominal):.2f} % a year")
print(f"GDP, volumes {yearly(real):.2f} % a year")
print(f"GDP per person, volumes {yearly(real / pop):.2f} % a year")
$ python per_person_growth.py
GDP, current prices 3.24 % a year
GDP, volumes 1.23 % a year
GDP per person, volumes 0.95 % a year
Each line divides by one more thing. Prices take 2.01 points a year off nominal growth, from 3.24 to 1.23, and population growth another 0.28 points, leaving 0.95. The function yearly computes a compound rate from the two end years only, so a recession inside the span does not show in it. That is a choice of method, and it belongs next to the number when the number is printed.
28.6 A chart is a table a script wrote
Definition 28.6 (Reproducible computation)
A computation is reproducible when running its scripts again on the same inputs gives the same outputs, byte for byte, with no step done by hand.
Every chart of this book is drawn from a CSV file that a tested script wrote; no number in a chart was typed. When a source is revised, the scripts run again and every chart and every quoted number follows.
"""A chart is a table a script wrote: write it twice, compare the bytes."""
import hashlib
from pathlib import Path
from country import load
a = load("accounts")
t = a[["year", "real_gdp", "unemp_rate"]]
for run in (1, 2):
t.to_csv("chart.csv", index=False, lineterminator="\n")
digest = hashlib.sha256(Path("chart.csv").read_bytes()).hexdigest()
print(f"run {run}: sha256 {digest[:16]}")
print(Path("chart.csv").read_text().splitlines()[:3])
$ python write_chart_table.py
run 1: sha256 0bf49671a392deed
run 2: sha256 0bf49671a392deed
['year,real_gdp,unemp_rate', '2000,197403,6.0', '2001,198967,6.3']
A digest is a fingerprint of a file’s bytes: a change of one character anywhere gives a different one. Two runs that print the same sixteen hexadecimal digits wrote the same file. The fixed line ending matters here. Left to its default, the operating system chooses the end-of-line character, and two machines could write the same numbers in different bytes.
On the record — A spreadsheet and two choices
A widely cited study of public debt and growth (Reinhart and Rogoff 2010) in 20 advanced economies over 1946–2009 reported that country-years with public debt above of GDP had average growth of . Working from the authors’ own spreadsheet, a replication found that a coding error left five countries out of an average, that some available years were excluded, and that the averages were weighted unusually; corrected, the growth rate was (Herndon, Ash and Pollin 2014). A formula typed into a cell is invisible on the page that cites its result. A script that can be rerun, and a check that recomputes a published number, are how such errors are found.
Exercises
Exercise 28.1 ★
Give the shape, the unit of observation and the key of the tables printed by Outputs 28.1 and 28.2, and of the monthly series of Listing 28.6.
Solution
Solution of Exercise 28.1.
First look: 18 rows and 6 columns, a country in a year, key (iso3, year). Long table: 25 rows and 3 columns, same unit and key; wide table: 5 rows (countries) and 5 columns (years), key iso3. Monthly series: one value per month, key (year, month).
Exercise 28.2 ★
From Output 28.6, give the twelve-month change of the unadjusted and the adjusted index in June 2022. Why do they differ?
Solution
Solution of Exercise 28.2.
unadjusted, adjusted. Over twelve months the season cancels almost exactly; the small difference comes from the adjusted series’ factors changing slowly from year to year.
Exercise 28.3 ★
Prices rise by in a month. Give the annualised rate.
Solution
Solution of Exercise 28.3.
.
Exercise 28.4 ★
Which aggregation from months to years — mean, sum or last value — suits the unemployment rate, exports, the consumer price index, the population and government debt?
Solution
Solution of Exercise 28.4.
Unemployment rate: mean. Exports (a flow): sum. Consumer price index: mean. Population: mean for a yearly average, or the last value for the end of the year, said which. Debt (a stock): last value.
Exercise 28.5 ★★
Merge the Penn World Table and the Maddison Project table for 2019 on (iso3, year). How many keys match, and how many are found in one table only? Name two kinds of unit in each group.
Solution
Solution of Exercise 28.5.
161 keys match; 24 are only in the Penn table and 8 only in the Maddison table. Only in Penn: small economies such as Aruba, Anguilla and the Cayman Islands. Only in Maddison: units that no longer exist (the Soviet Union, Yugoslavia, Czechoslovakia, kept as historical aggregates) and economies Penn does not cover (Afghanistan, Cuba).
Exercise 28.6 ★★
Rebase Brenland’s consumer price index to 2025 = 100 and compute its average log growth from 2016 to 2025.
Solution
Solution of Exercise 28.6.
in 2015, in 2020 and in 2025; mean log growth log points a year.
Exercise 28.7 ★★
A quarterly series is for , with a season of , , and in quarters 1 to 4. Using the differences from a centred four-quarter moving average, recover the season.
Solution
Solution of Exercise 28.7.
The centred moving average of is exactly , since the season sums to zero over four quarters. The differences are then , and their averages by quarter are , , and .
Exercise 28.8 ★★
A country’s population falls. Predict the sign of the difference between the growth of its GDP per person and the growth of its GDP.
Solution
Solution of Exercise 28.8.
Positive: GDP per person grows faster than GDP, by about the rate at which population falls.
Exercise 28.9 ★★
Recompute the three growth rates of Listing 28.10 for 2000–2019. Which of the three changes most when the pandemic years are left out?
Solution
Solution of Exercise 28.9.
nominal, in volumes, per person. The nominal rate changes most (from to ): the inflation of 2021–23 is left out.
Exercise 28.10 ★★★
Write adjust_q, the quarterly version of adjust, and test it on a series with a known multiplicative season of , , and and a trend of a quarter.
Solution
Solution of Exercise 28.10.
As adjust, with a four-quarter moving average centred with weights , , , , and factors averaged by quarter. On the known series it recovers , , and : the season to within .
Exercise 28.11 ★★★
A colleague’s export of the Penn table writes country codes in lower case. A left join of the World Bank table with it runs without error. What does it return, and which check would catch the error?
Solution
Solution of Exercise 28.11.
All 199 rows of the World Bank table, none with Penn data: no code matches, and a left join keeps the rows with empty columns. Counting the matches (indicator=True) or checking that the joined columns are not all empty would catch it; after converting the codes to upper case, 178 rows match.
Exercise 28.12 ★★★
A real GDP series was computed with a deflator whose base year is not the one stated. What simple check would reveal it?
Solution
Solution of Exercise 28.12.
In the stated base year, real and nominal GDP must be equal. If they are not, the deflator’s base year is not the one stated.
28.7 Problem: Brenland’s Open-Data Portal
Problem 28.1
Weekend problem — checking a portal’s numbers
Brenland’s statistical office (invented) publishes its accounts, its trade with Kestria and its consumer basket, and a headline: “real growth, 2015–2025: a year”. Its trade file has one year mistyped. Its monthly consumer price index for 2015–2024 is built from the yearly index, with a seasonal factor of in month and a little noise. Each answer comes from a script.
Part I — Loading and checking.
- How many rows does the accounts table have, and which years?
- Check that in every year.
- Check that the deficit equals spending minus revenue.
- How many rows do the trade and basket tables have, and why 130?
- What is the price index in 2015, and why check it?
- Why run these checks before any analysis?
Part II — Joining.
- Join the accounts and the portal’s trade file on
yearwith an indicator. Which year of the accounts finds no match? - Which year appears twice in the trade file?
- What would
validate="one_to_one"have done? - Fix the file, and join again.
- What share of Brenland’s exports went to Kestria in 2025?
- What were those exports worth in kests?
Part III — The monthly index.
- What is the true seasonal factor of June?
- What factor does
adjustrecover for June? - And for December?
- What is the largest error of the recovered factors?
- Compare the twelve-month change in December 2024 with the change in the yearly average from 2023 to 2024.
- Which of the two would you report for 2024, and why?
Part IV — The headline.
- How did the portal obtain ?
- Compute real growth with the deflator.
- Compute the mean log growth, and say why it is a little lower.
- Compute growth of real GDP per person.
- Compute growth of nominal GDP divided by the consumer price index, and say why it differs from the answer to question 20.
- State the result: the corrected real growth of Brenland, 2015–2025.
Solution
Solution of Problem 28.1.
1. 26 rows, 2000 to 2025.
2. The largest absolute difference is 0: the identity holds.
3. The largest difference is 0.
4. 26 and 130: five goods in each of 26 years.
5. 100: the index is based in 2015, as stated.
6. A table that fails its own identities makes every later result wrong; it is cheaper to find that out first.
7. 2021.
8. 2012: the 2021 row was typed as 2012.
9. Raised an error, because 2012 appears twice in the trade file.
10. With 2021 restored, all 26 years match one to one.
11. .
12. million kests.
13. .
14. .
15. true and recovered.
16. .
17. over the twelve months to December 2024, against for the yearly average.
18. The yearly average for a year’s inflation, as the statistical office publishes it; the December change for where inflation stood at the end of the year. Either, if the report says which.
19. From nominal GDP: , which mixes price and volume.
20. a year.
21. log points: for .
22. a year.
23. : the consumer price index rose faster than the GDP deflator ( against ), since it prices a different basket.
24. The corrected real growth of Brenland, 2015–2025, is a year, not the portal’s , which was nominal growth.