ECON 290 · Economic Data and Computing

Summaries and Regressions in Code

Use a few lines of Python to describe a data set, fit a straight line, and read the results without being fooled.

Key takeaways

  • A summary reports the center and the spread of a column, using numbers such as the mean, median and standard deviation.
  • A regression fits a line, written y = a + b × x, that best describes how one variable moves with another.
  • The slope b says how much y changes, on average, when x rises by one unit; the intercept a is the fitted value when x is zero.
  • R² tells you what share of the ups and downs in y the line accounts for, but it does not prove that x causes y.
  • Always check a regression against the plain data and your own sense of the numbers before you trust it.

Picture Priya, who runs a juice stand at a weekend market. Each weekend she spends some money on a banner and a sandwich board, and each weekend she records her sales. After five weekends she has a small table and a big question: does spending more on ads actually bring in more money?

She could squint at the numbers. Or she could ask the computer for two things: a short summary of each column, and the best straight line through the data. That is what this lesson is about. You have met the ideas of describing data and fitting lines in statistics; here you will see how a few lines of code do the arithmetic, and, just as important, how to read what comes back.

Step one: summarize each column

Before fitting anything, describe what you have. Suppose Priya's weekly sales, in hundreds of dollars, were 12, 15, 9, 14, 20 and 10. In Python, with the tools from the programming lesson, that is one line.

import pandas as pd

sales = pd.Series([12, 15, 9, 14, 20, 10])
print(sales.describe())

The describe command reports the count, mean, standard deviation, minimum, quartiles and maximum. Here is what those numbers mean and how to check each by hand.

  • Count: 6 values.
  • Mean: (12 + 15 + 9 + 14 + 20 + 10) ÷ 6 = 80 ÷ 6 ≈ 13.33.
  • Median: sort the values to get 9, 10, 12, 14, 15, 20. The middle two are 12 and 14, so the median is 13.
  • Standard deviation: a typical distance from the mean. We work it out below.

Why report both mean and median? The mean is pulled by unusual values; the median is not. Here they are close (13.33 and 13), which suggests no wild outlier. If one weekend had sold 200 instead of 20, the mean would leap while the median hardly moved. Seeing both helps you spot that.

The standard deviation, worked out

The standard deviation measures spread. Here is the recipe, with Priya's six numbers and a mean of 13.33.

Value   Distance from mean   Squared
12         -1.33              1.78
15         +1.67              2.78
9          -4.33             18.78
14         +0.67              0.44
20         +6.67             44.44
10         -3.33             11.11
                      Sum:   79.33

Divide the sum by n − 1, which is 5, to get 79.33 ÷ 5 ≈ 15.87. That is the variance. The standard deviation is its square root: √15.87 ≈ 3.98. So a typical weekend lands about 4 hundred dollars from the 13.33 average. (Statistics programs divide by n − 1 for a sample; some tools divide by n unless you ask. Check which your tool uses, because the answers differ.)

Mean and spread in one line each
mean + sd = 13.33 ± 3.98 mean = Center Add all values, divide by how many: 80 ÷ 6 ≈ 13.33. sd = Spread Square root of the sum of squared distances divided by n − 1: about 3.98. 13.33 ± 3.98 = A rough range Many weekends should fall within about one sd of the mean. mean + sd = 13.33 ± 3.98 mean = Center Add all values, divide by how many: 80 ÷ 6 ≈ 13.33. sd = Spread Square root of the sum of squared distances divided by n − 1: about 3.98. 13.33 ± 3.98 = A rough range Many weekends should fall within about one sd of the mean.

Step two: the question about two variables

Now the real question. Priya also recorded her weekly ad spending, in hundreds of dollars, next to the sales for five particular weekends.

Weekend   Ad spend (x)   Sales (y)
1              1             3
2              2             5
3              3             6
4              4             9
5              5            12

Both are in hundreds of dollars. A regression finds the line y = a + b × x that sits as close as possible to these points. "As close as possible" has a precise meaning. For each point, measure the vertical gap between the point and the line, square it and add up all the squares. The line that makes this total smallest is the ordinary least squares line, often shortened to OLS. If you want the full story of why, see the lesson on least squares.

In code, using a popular library called statsmodels, it looks like this.

import pandas as pd
import statsmodels.formula.api as smf

df = pd.DataFrame({"ads": [1, 2, 3, 4, 5],
                   "sales": [3, 5, 6, 9, 12]})
model = smf.ols("sales ~ ads", data=df).fit()
print(model.summary())

The formula "sales ~ ads" reads "sales explained by ads". The fit call does the arithmetic. The summary prints a long table. You need only a few numbers from it.

Doing the arithmetic by hand

Here is the calculation the computer does. The mean of x is 3 and the mean of y is 7. For each weekend, multiply the distance of x from 3 by the distance of y from 7.

x    y    (x-3)   (y-7)   product   (x-3) squared
1    3     -2      -4       8          4
2    5     -1      -2       2          1
3    6      0      -1       0          0
4    9     +1      +2       2          1
5   12     +2      +5      10          4
              Sum:         22         10

The slope is the sum of products divided by the sum of squares: b = 22 ÷ 10 = 2.2. The intercept makes the line pass through the point of means: a = 7 − 2.2 × 3 = 7 − 6.6 = 0.4.

So the fitted line is sales = 0.4 + 2.2 × ads.

Priya's five weekends and the fitted line
Sales ($ hundreds) 3 7 Fitted line Means Ad spend ($ hundreds) Sales ($ hundreds) 3 7 Fitted line Means Ad spend ($ hundreds)

The line passes through the point of means (3, 7). Each hundred dollars of ads goes with about 2.2 hundred dollars more sales.

Reading the output

The program's table would show a coefficient of 2.2 for ads and 0.4 for the intercept. Here is how to read them in plain words.

The slope, 2.2. On average, an extra hundred dollars of ads goes with an extra 2.2 hundred dollars of sales. Notice the careful phrasing: "goes with", not "causes". We will return to that.

The intercept, 0.4. The line says that at zero ad spend, sales would be 0.4 hundred dollars. Do not lean on this too hard. Priya never tried zero ads, and a line is only a safe guide inside the range of data it has seen.

The fitted values and residuals. Plug each x into the line to get the fitted y: 2.6, 4.8, 7.0, 9.2 and 11.4. The gap between actual and fitted is the residual: 0.4, 0.2, −1.0, −0.2 and 0.6. These add up to zero, as they always do with an intercept in the model.

R². The statistic R² compares leftover error with total variation. The squared residuals add to 0.16 + 0.04 + 1.00 + 0.04 + 0.36 = 1.60. The squared distances of y from its mean (the y deviations are −4, −2, −1, 2 and 5) add to 16 + 4 + 1 + 4 + 25 = 50. So R² = 1 − 1.60 ÷ 50 = 0.968. The line accounts for about 97 percent of the ups and downs in Priya's sales across these five weekends.

Where R-squared comes from
Priya's regression Sums of squares Variation in sales Total variation (y from its mean) 50 Left unexplained (residuals) (1.60) Explained by the line 48.40 R-squared = 48.4 ÷ 50 0.97 Priya's regression Sums of squares Variation in sales Total variation (y from its mean) 50 Left unexplained (residuals) (1.60) Explained by the line 48.40 R-squared = 48.4 ÷ 50 0.97

Total variation of 50 splits into 48.4 explained and 1.6 left over. Example with made-up numbers.

Using the line to predict, and checking the prediction

Once you have a fitted line, you can use it. Priya wonders what a sixth weekend with 6 hundred dollars of ads might bring. Plug in: 0.4 + 2.2 × 6 = 0.4 + 13.2 = 13.6 hundred dollars. In code, one more line asks the model for this.

new = pd.DataFrame({"ads": [6]})
print(model.predict(new))

The answer, 13.6, is a guess, not a promise. Weekends 1 to 5 each landed off the line by up to a full hundred dollars, so a sixth weekend will probably land off it too. A good report gives the prediction and says how uncertain it is.

Notice also that 6 is just outside the range of ad spending Priya has tried (1 to 5). Going a little past the data is risky. Going far past it is much worse. A line fitted on 1 to 5 says nothing reliable about spending 50 hundred dollars; at some point the market is saturated and extra ads stop helping, and a straight line cannot show that.

One good check is to compare your fitted values with the real ones, row by row. In the example the biggest miss is weekend 3, where the line predicted 7.0 but Priya sold 6. That is a miss of 1.0, which is large next to the other misses of 0.2 to 0.6. It deserves a look. Was it rainy? Did a competitor open next door? Residuals that stand out are often where the story is.

Adding more variables

Priya can add other columns, such as whether it rained or whether a festival was on. A regression with several explanatory variables is a multiple regression. In code, you just add terms to the formula: "sales ~ ads + rain". The slope on ads now means the average change in sales for an extra hundred dollars of ads, holding rain the same.

That phrase, "holding the other things the same", is why economists like multiple regression. It lets you compare weekends that are alike in the ways you have measured. But it only holds constant what you have included. If something important is missing from the table, the slope can still mislead.

What the output cannot tell you

A tidy regression table feels authoritative, but it answers a narrow question.

It does not prove cause. Perhaps Priya spends more on ads on weekends when she already expects a big crowd, such as a festival. Then crowds drive both ads and sales, and the slope overstates what ads alone can do. The lesson on fitting a line and later lessons on causal evidence take this up.

Five points is very few. The computer will happily fit a line to five points, and it will report a clean R². But with so little data, a few unusual weekends could change the answer a lot. Output tables also report standard errors and p-values, which show how much the slope might vary from sample to sample. Look at them, not just at the slope.

A high R² does not make a good model. With few points, or with two trends that rise over time together, R² can be high even when nothing real connects them. Always plot the data first.

Outliers can pull the line. Change the last weekend's sales from 12 to 30 and the slope jumps. Plot the points and look for ones that sit far from the rest.

Habits for regression work in code

Work in small steps, in this order: look at the data, summarize it, plot it, fit the model, then read the results. If a coefficient looks wrong, go back to the data. A sign you did not expect, such as ads lowering sales, is often a clue about a typo, a wrong unit or a merge gone bad, as in the lesson on cleaning and merging.

Finally, save your code and write down which file you used. A regression you cannot rerun is a regression no one can check. The lesson on reproducible work shows how.

Words to know

Mean the sum of the values divided by how many there are.

Median the middle value when the numbers are sorted from smallest to largest.

Standard deviation a typical distance of the values from their mean, the square root of the variance.

Regression a method that fits a line (or curve) describing how one variable moves with another.

Slope the average change in y for a one-unit rise in x.

Residual the gap between an actual value and the value the fitted line predicts.

R² the share of the variation in y that the fitted line accounts for.

Check yourself

  1. For the values 4, 6 and 8, what are the mean and the median?
  2. Using the values 12, 15, 9, 14, 20 and 10, explain in a sentence why the sum of squared distances is divided by 5 rather than 6 to get the variance.
  3. Priya's ad data are x = 1, 2, 3, 4, 5 and y = 3, 5, 6, 9, 12. What does the fitted line predict for sales if she spends 4 hundred dollars on ads?
  4. The slope is 2.2. Say in plain words what that means, without using the word "cause".
  5. The residual for weekend 3 is −1.0. What was the actual value, and what did the line predict?
  6. Explain why a high R² of 0.968 on five weekends does not prove that ads raise sales.
Show the answers
  1. Mean = (4 + 6 + 8) ÷ 3 = 6; the median is the middle value, also 6.
  2. This is a sample, so we divide by n − 1 = 5; the standard sample formula corrects for the fact that the mean was estimated from the same data.
  3. Sales = 0.4 + 2.2 × 4 = 0.4 + 8.8 = 9.2 hundred dollars, which is $920.
  4. On average, weekends with one more hundred dollars of ad spending had 2.2 hundred dollars more sales.
  5. The actual value was 6 and the line predicted 7.0 (0.4 + 2.2 × 3), so 6 − 7.0 = −1.0.
  6. R² only measures fit within these five weekends; other factors, such as a festival crowd, could drive both ads and sales, and five points are too few to be sure.

A free self-study program written for 4Economics with AI writing tools and not reviewed line by line by a person. It is not an accredited degree and awards no credit. Check anything you rely on against a textbook or primary source. Report an error.

In this unit: Working with data

  1. Spreadsheets for Economic AnalysisLearn to organize data in rows and columns, write formulas for growth and averages, and avoid common spreadsheet traps.10 min
  2. Charts That Tell the TruthLearn how axes, scales and choices of chart type can mislead, and how to draw honest charts of economic data.10 min
  3. Cleaning and Merging DataRaw data is messy. Learn to find and fix common problems, then join two tables safely on a shared key.12 min
  4. A First Look at Programming for Data AnalysisMeet variables, lists, loops, functions and tables in Python, using small economic examples you can follow line by line.11 min
  5. Summaries and Regressions in CodeUse a few lines of Python to describe a data set, fit a straight line, and read the results without being fooled.11 min
  6. Reproducible Work: Files, Notes and VersionsOrganize files, write down your steps and save versions so that you, or anyone else, can redo an analysis and get the same answer.11 min
  7. Time Series Basics: Trends, Growth Rates and Moving AveragesLearn to read data that comes in time order: find the trend, compute growth rates correctly, and smooth noise with a moving average.10 min
  8. Presenting Data Findings to Non-ExpertsTurn an analysis into a clear message for busy readers: lead with the answer, choose one chart, and be honest about doubt.10 min

In the news