经济学 · 第 3 册 · 本科一年级

University Economics — Year 1

本书暂未推出简体中文版。现有版本:English。

University Economics — Year 1 · 本科一年级

29Describing Data

In 1978, 2,490 American men of a household panel earned on average 21,554 dollars of 1982, and 51.4%51.4\% of them earned less than that average. (The samples of this chapter and the next three measure earnings in dollars of 1982.)

In the United States in 2022, the richest hundredth of the population had an average income 9.37 times the median. A mean is a fine summary of a symmetric distribution and a poor one of a skewed one, and incomes are skewed. This chapter describes data before any model: distributions, their centre and spread, how two variables move together, how means differ across groups — and the traps in each.

Average income per person of each hundredth of the population, United States, 2022, dollars a day at 2021 purchasing power, on an ordinary axis (left) and a logarithmic axis (right).
Average income per person of each hundredth of the population, United States, 2022, dollars a day at 2021 purchasing power, on an ordinary axis (left) and a logarithmic axis (right). Source: World Bank, Poverty and Inequality Platform (percentiles)

On the ordinary axis the bottom four-fifths are squeezed together and the top hundredth stands alone at 629 dollars a day. On the logarithmic axis, equal distances are equal ratios: the median, 67 dollars, is 2.7 times the tenth hundredth and 0.4 times the ninetieth.

You already know

Mean, median, quartiles, variance and standard deviation were met in the mathematics series; the Lorenz curve, the Gini coefficient and top shares at school. Python and pandas are Chapter 28.

How it is measured — Income in a survey

The opening chart’s incomes come from a household survey. Household income is divided by the number of members, which assumes that everyone in the household shares equally; and wealthy households are less likely to answer, so the distribution may have too thin a tail at the top. Tax records, which reach the top better, give larger top shares.

29.1 Histograms and quantiles

Definition 29.1 (Histogram)

A histogram divides the range of a variable into bins and draws over each a bar whose area is the share of observations in the bin: its height is the share divided by the bin’s width, a density, so that the areas sum to 1 whatever the widths.

Definition 29.2 (Empirical distribution function)

The empirical distribution function of a sample x1,…,xnx_1, \dots, x_n is F^(t)=1n#{i:xi≤t}\hat F(t) = \frac1n\#\{i : x_i \le t\}, the share of observations at or below tt.

Definition 29.3 (Quantile, percentile)

The quantile of order pp is the smallest value tt with F^(t)≥p\hat F(t) \ge p (or an interpolation between two observations, as pandas does by default); the pp-th percentile is the quantile of order p/100p/100.

"""Earnings in 1978 of 2,490 American men (PSID sample): a histogram and quantiles."""

import numpy as np
from econdata import nsw

earn = nsw("psid_controls").re78  # dollars of 1982
counts, edges = np.histogram(earn, bins=np.arange(0, 130_001, 10_000))
width = edges[1] - edges[0]
density = counts / (len(earn) * width)  # the bars' areas sum to 1
for lo, n, d in zip(edges[:-1], counts, density):
    print(f"{lo:>7,.0f} to {lo + width:>7,.0f}: {n:5d}  density {d:.2e}")

q = earn.quantile([0.1, 0.25, 0.5, 0.75, 0.9]).round(0)
print(q.to_string())
print(
    f"mean {earn.mean():,.0f}; share below the mean {(earn < earn.mean()).mean():.3f}"
)
Listing 29.1. A histogram as a table of densities, and five quantiles. code/bachelor-1/29-describing-data/listings/histogram.py
$ python histogram.py
      0 to  10,000:   562  density 2.26e-05
 10,000 to  20,000:   623  density 2.50e-05
 20,000 to  30,000:   730  density 2.93e-05
 30,000 to  40,000:   370  density 1.49e-05
 40,000 to  50,000:   108  density 4.34e-06
 50,000 to  60,000:    41  density 1.65e-06
 60,000 to  70,000:    17  density 6.83e-07
 70,000 to  80,000:    20  density 8.03e-07
 80,000 to  90,000:    11  density 4.42e-07
 90,000 to 100,000:     4  density 1.61e-07
100,000 to 110,000:     1  density 4.02e-08
110,000 to 120,000:     2  density 8.03e-08
120,000 to 130,000:     1  density 4.02e-08
0.10        0.0
0.25    11526.0
0.50    20688.0
0.75    29554.0
0.90    38421.0
mean 21,554; share below the mean 0.514
Output 29.1. A long right tail: a few men above 100,000 dollars, a tenth at zero.

29.2 Mean, variance and skewness

Definition 29.4 (Skewness)

The skewness of a sample is 1n∑i(xi−xˉ)3/s3\frac1n\sum_i (x_i - \bar x)^3/s^3, with s2=1n∑i(xi−xˉ)2s^2 = \frac1n\sum_i (x_i - \bar x)^2: positive when the right tail is longer, negative when the left one is, zero for a symmetric distribution.

"""Mean, standard deviation and skewness of earnings and of their logarithm."""

import numpy as np
from econdata import nsw
from scipy.stats import skew

earn = nsw("psid_controls").re78
pos = earn[earn > 0]  # the logarithm needs positive earnings
print("zero earnings:", (earn == 0).sum())
for name, x in [("earnings", pos), ("log earnings", np.log(pos))]:
    print(
        f"{name:13s} mean {x.mean():10.3f}  sd {x.std():10.3f}  skewness {skew(x):6.3f}"
    )
Listing 29.2. The first three moments, of earnings and of their logarithm. code/bachelor-1/29-describing-data/listings/moments.py
$ python moments.py
zero earnings: 286
earnings      mean  24350.845  sd  14326.321  skewness  1.645
log earnings  mean      9.897  sd      0.746  skewness -1.913
Output 29.2. Positive earnings skewed to the right (1.6451.645); their logarithm skewed to the left (−1.913-1.913).

The logarithm pulls in the long right tail, but it stretches the left one: a man with very low positive earnings sits far below the others on a log scale. In Brenland’s survey, where no household has income near zero, the logarithm of disposable income has a skewness of −0.123-0.123, against 1.4361.436 for the level (weekend problem). Whether the logarithm makes a distribution symmetric depends on its bottom as much as on its top.

29.3 Covariance and correlation

Definition 29.5 (Sample covariance, correlation coefficient)

The sample covariance of xx and yy is sxy=1n−1∑i(xi−xˉ)(yi−yˉ)s_{xy} = \frac1{n-1}\sum_i (x_i - \bar x)(y_i - \bar y); the correlation coefficient is r=sxy/(sxsy)r = s_{xy}/(s_x s_y).

Proposition 29.6 (Range of the correlation)

−1≤r≤1-1 \le r \le 1, with ∣r∣=1|r| = 1 if and only if the points lie on a straight line that is not horizontal or vertical.

Proof. Let ai=xi−xˉa_i = x_i - \bar x and bi=yi−yˉb_i = y_i - \bar y. By the Cauchy–Schwarz inequality, (∑iaibi)2≤∑iai2∑ibi2(\sum_i a_ib_i)^2 \le \sum_i a_i^2 \sum_i b_i^2, so sxy2≤sx2sy2s_{xy}^2 \le s_x^2 s_y^2 and r2≤1r^2 \le 1. Equality holds when b=λab = \lambda a for some λ≠0\lambda \ne 0, that is yi−yˉ=λ(xi−xˉ)y_i - \bar y = \lambda(x_i - \bar x) for every ii. ∎

"""Covariance and correlation: earnings in 1975 and 1978, and a parabola."""

import numpy as np
from econdata import nsw

d = nsw("psid_controls")
x, y = d.re75, d.re78
n = len(d)
cov = ((x - x.mean()) * (y - y.mean())).sum() / (n - 1)
r = cov / (x.std() * y.std())  # pandas' std divides by n - 1 too
print(f"by hand:     cov {cov:,.0f}  r {r:.4f}")
print(f"with pandas: cov {x.cov(y):,.0f}  r {x.corr(y):.4f}")

rng = np.random.default_rng(2026)
u = rng.uniform(-1, 1, 1000)
v = u**2  # v is a function of u, yet ...
print(f"parabola:    r {np.corrcoef(u, v)[0, 1]:.4f}")
Listing 29.3. Covariance and correlation by hand and with pandas, and a correlation that misses a parabola. code/bachelor-1/29-describing-data/listings/covariance.py
$ python covariance.py
by hand:     cov 154,706,518  r 0.7315
with pandas: cov 154,706,518  r 0.7315
parabola:    r 0.0672
Output 29.3. Earnings in 1975 and 1978: r=0.73r = 0.73. A parabola: rr near 0.

A correlation measures how close the points are to a straight line. It says nothing about a relation that is not linear: on a symmetric range, v=u2v = u^2 is entirely determined by uu, and the correlation is near zero.

Three seeded samples of 200 points: close to a line, a cloud, and a parabola whose correlation is near zero although y is a function of x.
Three seeded samples of 200 points: close to a line, a cloud, and a parabola whose correlation is near zero although yy is a function of xx.

29.4 Conditional means

Definition 29.7 (Conditional mean (in data))

The conditional mean of yy given x=ax = a in a sample is the mean of yy over the observations with x=ax = a; as a function of aa, it describes how the average of yy changes with xx.

"""Conditional means: earnings in 1978 by years of schooling (PSID sample)."""

from econdata import nsw

d = nsw("psid_controls")
d = d[d.education.between(8, 17)]
g = d.groupby("education").re78.agg(["count", "mean", "median"]).round(0)
print(g.to_string())
Listing 29.4. Mean and median earnings by years of schooling. code/bachelor-1/29-describing-data/listings/group_means.py
$ python group_means.py
           count     mean   median
education                         
8            148  14888.0  13300.0
9            104  16130.0  13743.0
10           163  17797.0  17733.0
11           162  16153.0  14149.0
12           853  20564.0  20688.0
13           135  20934.0  22166.0
14           184  24465.0  25121.0
15            64  27804.0  25687.0
16           283  30184.0  28816.0
17           211  32285.0  31032.0
Output 29.4. Earnings rise with schooling, with a dip at 11 years and a step at 12.
Mean earnings in 1978 by years of schooling, PSID comparison sample: the 2,307 men with 8 to 17 years of schooling (counts above the bars).
Mean earnings in 1978 by years of schooling, PSID comparison sample: the 2,307 men with 8 to 17 years of schooling (counts above the bars). Source: LaLonde (1986) and Dehejia and Wahba (1999) samples of the National Supported Work data

The samples were assembled to test whether non-experimental methods can reproduce the result of an experiment (LaLonde 1986; Dehejia and Wahba 1999).

The conditional means describe; whether a year of schooling causes the step from 16,15316{,}153 to 20,56420{,}564 dollars between 11 and 12 years is the question of Chapter 32.

29.5 Traps

Definition 29.8 (Composition effect, Simpson’s paradox)

A composition effect is a change or difference in an overall mean that comes from the shares of the groups rather than from the means within them. Simpson’s paradox is its extreme case: a comparison that goes one way within every group and the other way overall.

"""Brenland's survey: older and younger households, overall and by work."""

from country import load

h = load("households")
h["older"] = h.age_head >= 50  # head aged 50 or more
h["works"] = h.hours > 0
overall = h.groupby("older").disposable.mean().round(0)
print("overall:", overall.to_dict())
by_work = h.groupby(["works", "older"]).disposable.agg(["count", "mean"]).round(0)
print(by_work.to_string())
print("share working:", h.groupby("older").works.mean().round(3).to_dict())
Listing 29.5. Older and younger households in Brenland’s survey, overall and within working and non-working households. code/bachelor-1/29-describing-data/listings/simpson.py
$ python simpson.py
overall: {False: 25301.0, True: 24519.0}
             count     mean
works older                
False False     57   9353.0
      True     504  18370.0
True  False    968  26240.0
      True     471  31098.0
share working: {False: 0.944, True: 0.483}
Output 29.5. Older households have more income within each group, and less overall.
Simpson’s paradox in Brenland’s survey: within non-working and within working households, households with older heads have more income; overall they have less, because 51.7\% of them do not work, against 5.6\% of the others.
Simpson’s paradox in Brenland’s survey: within non-working and within working households, households with older heads have more income; overall they have less, because 51.7%51.7\% of them do not work, against 5.6%5.6\% of the others.

On the record — Admissions by department

In 1973 the six largest departments of a graduate school admitted 44.5%44.5\% of 2,691 male applicants and 30.4%30.4\% of 1,835 female applicants. Department by department the gap largely disappeared: women had applied more often to the departments that admitted a small share of all applicants. The pooled figures showed a pattern that the departments’ own decisions did not (Bickel, Hammel and O’Connell 1975).

Definition 29.9 (Top-coding, censoring)

A variable is top-coded when values above a cap are recorded at the cap. More generally, it is censored when values beyond a limit are known only to lie beyond it.

"""The CPS sample: earnings above a cap were recorded at the cap."""

from econdata import nsw

earn = nsw("cps_controls").re78
cap = earn.max()
at_cap = earn == cap
n_cap = at_cap.sum()
print(f"cap {cap:,.2f}; men at the cap {n_cap} of {len(earn)} ({at_cap.mean():.3f})")
print(f"mean as recorded       {earn.mean():10,.0f}")
print(f"mean without the capped {earn[~at_cap].mean():10,.0f}")
print(f"median                 {earn.median():10,.0f}")
print(
    "the true mean is at least", f"{earn.mean():,.0f}"
)  # capped values are lower bounds
Listing 29.6. A quarter of a sample at the cap. code/bachelor-1/29-describing-data/listings/top_coding.py
$ python top_coding.py
cap 25,564.70; men at the cap 4145 of 15992 (0.259)
mean as recorded           14,847
mean without the capped     11,097
median                     16,422
the true mean is at least 14,847
Output 29.6. 4,145 men recorded at 25,564.70 dollars: the recorded mean is a lower bound.
Earnings in 1978 in dollars of 1982, density per 100,000 dollars, bins of 2,000 dollars: PSID comparison sample (blue) and CPS comparison sample (red), values above 60,000 put in the last bin.
Earnings in 1978 in dollars of 1982, density per 100,000 dollars, bins of 2,000 dollars: PSID comparison sample (blue) and CPS comparison sample (red), values above 60,000 put in the last bin. Source: National Supported Work comparison samples

The CPS sample’s spike at its cap holds a quarter of the men. Every mean, variance or regression computed on it treats 25,564.70 dollars as their earnings.

Definition 29.10 (Outlier, trimmed mean)

An outlier is an observation far from the bulk of the data. The α\alpha-trimmed mean drops the fraction α\alpha of the observations at each end and averages the rest.

"""Mean, median and trimmed mean, with and without the largest earnings."""

from econdata import nsw
from scipy.stats import trim_mean

earn = nsw("nsw_dw").re78  # the 445 men of the experiment
top = earn.idxmax()
for name, x in [("all", earn), ("without the largest", earn.drop(top))]:
    print(
        f"{name:20s} n {len(x)}  mean {x.mean():7,.0f}  median {x.median():7,.0f}"
        f"  5% trimmed {trim_mean(x, 0.05):7,.0f}"
    )
print(f"largest {earn.max():,.0f}")
Listing 29.7. The mean moves with one observation; the median and the trimmed mean barely. code/bachelor-1/29-describing-data/listings/trimmed.py
$ python trimmed.py
all                  n 445  mean   5,301  median   3,702  5% trimmed   4,538
without the largest  n 444  mean   5,177  median   3,673  5% trimmed   4,507
largest 60,308
Output 29.7. Removing one man in 445 lowers the mean by 124 dollars and the median by 29.

Exercises

Exercise 29.1 ★

From the opening chart’s table, the median hundredth of Americans had 67.15 dollars a day in 2022 and the ninetieth 169.65. Give the ratio, and say where each lies on the logarithmic panel.

Solution

Solution of Exercise 29.1.

169.65/67.15=2.53169.65/67.15 = 2.53. On the logarithmic panel the ninetieth hundredth lies log⁡102.53=0.40\log_{10} 2.53 = 0.40 decades above the median, about as far above it as the tenth hundredth (24.55 dollars) lies below it.

Exercise 29.2 ★

Find the mean and the median of 22, 33, 33, 44, 1818. Which describes the typical value?

Solution

Solution of Exercise 29.2.

Mean 30/5=630/5 = 6, median 33. The median: one large value pulls the mean above four of the five numbers.

Exercise 29.3 ★

Two variables have a covariance of 12 and standard deviations of 3 and 5. Find their correlation.

Solution

Solution of Exercise 29.3.

r=12/(3×5)=0.8r = 12/(3 \times 5) = 0.8.

Exercise 29.4 ★

A country’s average wage falls in a year in which the wage of every occupation rises. Name the trap and give a mechanism.

Solution

Solution of Exercise 29.4.

A composition effect: employment shifted towards lower-paid occupations, for example because high-paid jobs were lost in a recession or many young workers entered low-paid ones.

Exercise 29.5 ★★

For the PSID men earning at least 5,000 dollars, compute the skewness of earnings and of their logarithm, and compare with Output 29.2.

Solution

Solution of Exercise 29.5.

For the 2,107 men earning at least 5,000 dollars, the skewness is 1.8781.878 for earnings and −0.238-0.238 for their logarithm: without the lowest earnings, the logarithm is close to symmetric.

Exercise 29.6 ★★

Replace the CPS sample’s capped values by 1.5 times the cap. By how much does the mean change? And the median?

Solution

Solution of Exercise 29.6.

The mean rises from 14,847 to 18,160 dollars, by 22.3%22.3\%; the median stays at 16,422, since it lies below the cap.

Exercise 29.7 ★★

From Output 29.4, give the step in mean earnings from 11 to 12 years of schooling, and the step from 12 to 16 years per year.

Solution

Solution of Exercise 29.7.

20,564−16,153=4,41120{,}564 - 16{,}153 = 4{,}411 dollars from 11 to 12 years; from 12 to 16 years, (30,184−20,564)/4=2,405(30{,}184 - 20{,}564)/4 = 2{,}405 dollars a year.

Exercise 29.8 ★★

Prove Proposition 29.6 without the Cauchy–Schwarz inequality, using ∑i(ai/∑a2±bi/∑b2)2≥0\sum_i (a_i/\sqrt{\sum a^2} \pm b_i/\sqrt{\sum b^2})^2 \ge 0.

Solution

Solution of Exercise 29.8.

With A=∑ai2A = \sqrt{\sum a_i^2} and B=∑bi2B = \sqrt{\sum b_i^2}, expanding gives ∑ai2/A2+∑bi2/B2±2∑aibi/(AB)=2±2r≥0\sum a_i^2/A^2 + \sum b_i^2/B^2 \pm 2\sum a_ib_i/(AB) = 2 \pm 2r \ge 0, so −1≤r≤1-1 \le r \le 1. Equality needs every term zero: bi/B=∓ai/Ab_i/B = \mp a_i/A, a straight line.

Exercise 29.9 ★★

A billionaire moves into a town of 10,000 people. Predict the change in mean and in median wealth.

Solution

Solution of Exercise 29.9.

The mean rises by about 109/10,001≈99,99010^9/10{,}001 \approx 99{,}990 dollars; the median barely moves (it shifts by half a step between two neighbouring values).

Exercise 29.10 ★★★

Department A admits 80 of 100 male and 18 of 20 female applicants; department B admits 10 of 50 male and 30 of 130 female applicants. Compute the admission rates by department and overall, and explain.

Solution

Solution of Exercise 29.10.

Men: 80%80\% in A, 20%20\% in B, 90/150=60%90/150 = 60\% overall. Women: 90%90\% in A, 30/130=23.1%30/130 = 23.1\% in B, 48/150=32%48/150 = 32\% overall. Women are admitted at a higher rate in each department and at a lower rate overall, because most of them applied to B, which admits few.

Exercise 29.11 ★★★

Show that xˉ\bar x minimises ∑i(xi−c)2\sum_i (x_i - c)^2 over cc, and that a median minimises ∑i∣xi−c∣\sum_i |x_i - c|.

Solution

Solution of Exercise 29.11.

The derivative of ∑(xi−c)2\sum(x_i - c)^2 is −2∑(xi−c)-2\sum(x_i - c), zero at c=xˉc = \bar x, and the function is convex. For ∑∣xi−c∣\sum|x_i - c|, moving cc up by a small hh changes the sum by hh times (the number of observations below cc minus the number above); the sum falls while more lie above and rises once more lie below, so it is smallest where half lie on each side: at a median.

Exercise 29.12 ★★★

A study reports a correlation of 0.10.1 between two variables. What observation would show that a strong relation lies behind it?

Solution

Solution of Exercise 29.12.

A scatter plot showing the points close to a curve that is not a line — a parabola, a threshold, a relation that holds in one group and is reversed in another. Correlations within groups, or of transformed variables, much larger than 0.10.1 would show it too.

29.6 Problem: Brenland’s Household Survey

Problem 29.1

Weekend problem — a survey, described

Brenland’s household survey of 2025 (invented) has 2,000 households, with disposable and gross income, the head’s age, schooling and hours, and the household’s size. Each answer comes from a script.

Part I — The distribution.

  1. Give the counts of disposable income in bins of 10,000 dalens.
  2. Give the counts of log⁡10\log_{10} of disposable income in bins of 0.20.2 from 3.83.8 to 55.
  3. Which histogram is closer to symmetric?
  4. Give the mean and the median.
  5. What share of households is below the mean?
  6. Why is the mean above the median?

Part II — Moments and quantiles.

  1. Give the standard deviation and the skewness.
  2. Give the skewness of the logarithm.
  3. Give the 10th and 90th percentiles and their ratio.
  4. What share of all disposable income goes to the top tenth of households?
  5. Why may a survey understate that share?

Part III — Income and schooling.

  1. Give mean gross income for heads with under 12, 12, 13–15 and 16 or more years of schooling.
  2. Give the correlation of schooling with gross income, and with its logarithm.
  3. Why might the correlation understate how much schooling and income are related?
  4. Does the table show that schooling raises income?

Part IV — The paradox. Split households by the head’s age (under 50, 50 or over) and by whether the head works.

  1. Give mean disposable income of each age group, overall.
  2. Give the four means within working and non-working households.
  3. Give the share working in each age group.
  4. Rebuild each overall mean as a weighted average of the within-group means.
  5. Compute the older households’ mean if they worked as often as the younger.
  6. Which comparison answers “do older households have more income when they work?”
  7. Which answers “do older households have more income?”
  8. Name the trap.
  9. What would a reader of the overall means alone conclude?
  10. State the result.
Solution

Solution of Problem 29.1.

1. 49, 731, 734, 315, 111, 40, 11, 7, 1, 1 (from 0 to 100,000).

2. 30, 249, 926, 598, 163, 15: 1,981 households. The other 19, all at the minimum of 6,000 dalens (log⁡106000=3.78\log_{10} 6000 = 3.78), lie below 3.83.8.

3. The logarithmic one: the level has a long right tail.

4. Mean 24,919.724{,}919.7 dalens; median 22,26522{,}265.

5. 60.8%60.8\%.

6. The distribution is skewed to the right: a few high incomes raise the mean and not the median.

7. 10,603.910{,}603.9 dalens; skewness 1.4361.436.

8. −0.123-0.123.

9. 14,789 and 38,991; ratio 2.642.64.

10. 19.3%19.3\%.

11. Wealthy households answer less often, and top incomes are under-reported.

12. 22,355; 24,775; 28,367; 35,762 dalens.

13. 0.3150.315; 0.3290.329 with the logarithm.

14. Income also depends on age, hours and luck, and retired households with high schooling have pensions rather than earnings; the relation may also be steeper at high schooling than a line allows.

15. No: it describes; people with more schooling may differ in other ways that raise income.

16. Under 50: 25,301; 50 or over: 24,519 dalens.

17. Not working: 9,353 (under 50) and 18,370 (50 or over). Working: 26,240 and 31,098.

18. 94.4%94.4\% under 50, 48.3%48.3\% at 50 or over.

19. 9681025×26,240+571025×9,353=25,301\tfrac{968}{1025} \times 26{,}240 + \tfrac{57}{1025} \times 9{,}353 = 25{,}301; 471975×31,098+504975×18,370=24,519\tfrac{471}{975} \times 31{,}098 + \tfrac{504}{975} \times 18{,}370 = 24{,}519 (with the shares rounded to 0.9440.944 and 0.4830.483 the sums are about 25,294 and 24,518).

20. 9681025×31,098+571025×18,370=30,390\tfrac{968}{1025} \times 31{,}098 + \tfrac{57}{1025} \times 18{,}370 = 30{,}390 dalens.

21. The within-group comparison.

22. The overall comparison, if the question is about households as they are.

23. Simpson’s paradox, a composition effect.

24. That households get poorer with age at every stage, when the difference comes from retirement.

25. Within working and within non-working households, older heads’ households have more income, yet overall their mean is lower by 782 dalens, because half of them no longer work.

本章定义的术语

在术语表中查看全部 1086 个术语