12.1. Correlation#
A regional manager at a retail chain spends part of the budget on advertising. Before moving more money into ads, the manager wants to know a simple thing: do stores that spend more on advertising also sell more? And if they do, how closely do the two move together?
This section gives you a picture and a number for that question. The picture is the scatter plot. The number is the correlation coefficient, written r, which summarizes how strongly two numerical variables are linearly associated. You will learn how to compute r, what it can and cannot tell you, and five situations in which r is easy to misread.
The data are in store_ad_sales.csv. They are a simulated teaching data set built to look like store records, not real stores. For each of 40 stores the file lists the region, weekly advertising spending (ad_spend, $1,000s), staff, store age, and weekly sales (sales, $1,000s). The same stores run through this whole chapter.
12.1.1. Looking for a Linear Pattern#
A scatter plot draws one dot per store. The horizontal position is the store’s advertising spending and the vertical position is its sales. Advertising spending is called the x variable and sales the y variable.
stores = pd.read_csv(path_data + 'store_ad_sales.csv')
stores.head()
| store | region | ad_spend | staff | store_age | sales | |
|---|---|---|---|---|---|---|
| 0 | S01 | North | 6.0 | 12 | 4 | 77.3 |
| 1 | S02 | South | 7.2 | 13 | 11 | 85.3 |
| 2 | S03 | North | 2.0 | 9 | 9 | 50.2 |
| 3 | S04 | North | 3.4 | 7 | 24 | 69.8 |
| 4 | S05 | North | 10.0 | 10 | 1 | 91.4 |
fig, ax = plt.subplots(figsize=(6, 4))
ax.scatter(stores['ad_spend'], stores['sales'], s=30)
ax.set_xlabel('Weekly advertising spending ($1,000s)')
ax.set_ylabel('Weekly sales ($1,000s)')
ax.set_title('Stores that spend more on ads tend to sell more')
plt.show()
The dots drift from the lower left to the upper right. Stores with higher advertising spending tend to have higher sales, so the two variables have a positive association. If higher values of x went with lower values of y, the association would be negative. If the dots showed no upward or downward drift, there would be no linear association. The two variables could still be related along a curve, as an example later in this section shows.
The dots also lie roughly along a straight line, with some scatter around it. When the pattern is close to a straight line, the association is called linear. The correlation coefficient is designed for exactly this kind of pattern.
To build intuition for how the number r (the correlation coefficient, defined in the next subsection) relates to the picture, the next cell simulates five groups of 100 points each. In each group, the two variables are generated so that r is close to a specified target. The generator is seeded, so the plots are the same every time.
rng = np.random.default_rng(1201)
targets = [-0.9, -0.5, 0, 0.5, 0.9]
fig, axes = plt.subplots(1, 5, figsize=(12, 2.8),
sharex=True, sharey=True)
for ax, target in zip(axes, targets):
x = rng.normal(0, 1, 100)
noise = rng.normal(0, 1, 100)
y = target * x + np.sqrt(1 - target ** 2) * noise
# y share x’s variation & independent variation
ax.scatter(x, y, s=10)
ax.set_title('r = ' + str(round(np.corrcoef(x, y)[0, 1], 2)), fontsize=11)
ax.set_xticks([])
ax.set_yticks([])
fig.suptitle('The closer r is to -1 or 1, the tighter the dots hug a line', y=1.04)
plt.show()
Read the gallery from left to right. At r near -0.9 the dots slope down and sit close to a line. At r near 0 they form a shapeless cloud. At r near 0.9 they slope up and sit close to a line again. The sign of r gives the direction of the drift, and its distance from 0 tells you how tightly the dots follow a line.
The advertising spending and sales plot looks like something between the middle and right panels. The next section gives the exact number.
12.1.2. Measuring Association with r#
Advertising spending and sales are on different scales, so their raw distances from the mean cannot be compared directly. To measure their association, ask whether stores that spend more than the average on advertising also tend to earn more than the average in sales. To make that comparison, convert each variable to standard units.
A value in standard units tells you how many standard deviations it lies above or below the mean of its variable (which is also the \(z\) score):
Here is a function that converts an array of numbers to standard units. It uses np.std, which divides by the number of values, as everywhere in this book. The pandas method .std() divides by n − 1 instead. Use np.std() here; mixing the two makes the mean of the products come out slightly too small. The values must not all be the same: a constant variable has a standard deviation of 0, so it has no standard units, and its correlation with anything is undefined.
def standard_units(values):
"Return values measured in standard deviations from their mean."
return (values - np.mean(values)) / np.std(values)
Using the \(z\) scores, the formula for \(r\) is:
Using the expanded form:
The correlation coefficient \(r\) is the mean of the products of the two variables in standard units. For each store, convert its advertising spending and its sales to standard units, multiply the two numbers, and then average the 40 products.
Why products? A store with above-average advertising spending and above-average sales has two positive standard-unit values, so the product is positive. A store below average on both has two negative values, and the product is again positive. A store that is high on one and low on the other gives a negative product. The sign of r depends on which kind of product outweighs the other, not just on how many stores fall into each kind. Stores far from average on both variables give large products and count the most, so a few large negative products can outweigh many small positive ones. That is also why a single unusual store can move r a lot, as the section on outliers shows.
The table below follows the calculation step by step for the first six stores.
steps = pd.DataFrame({
'store': stores['store'],
'ad_spend': stores['ad_spend'],
'sales': stores['sales'],
'ad_spend_su': standard_units(stores['ad_spend']),
'sales_su': standard_units(stores['sales']),
})
steps['product'] = steps['ad_spend_su'] * steps['sales_su']
steps.head(6).round(2)
| store | ad_spend | sales | ad_spend_su | sales_su | product | |
|---|---|---|---|---|---|---|
| 0 | S01 | 6.0 | 77.3 | 0.20 | -0.08 | -0.02 |
| 1 | S02 | 7.2 | 85.3 | 0.64 | 0.44 | 0.28 |
| 2 | S03 | 2.0 | 50.2 | -1.26 | -1.85 | 2.34 |
| 3 | S04 | 3.4 | 69.8 | -0.75 | -0.57 | 0.43 |
| 4 | S05 | 10.0 | 91.4 | 1.67 | 0.83 | 1.39 |
| 5 | S06 | 8.3 | 85.1 | 1.05 | 0.42 | 0.44 |
r = np.mean(steps['product'])
print('Mean of the 40 products (r):', round(r, 3))
Mean of the 40 products (r): 0.689
The r for advertising spending and sales is about 0.69. Most stores contribute a positive product, and a few contribute a negative one, but the average is clearly positive.
Since you will compute r often, package the steps in a function. It takes a table and the names of two columns. In the meantime, NumPy has np.corrcoef() for the correlation coefficient.
def correlation(table, x, y):
"Mean of the products of the standard units of two columns."
return np.mean(standard_units(table[x]) * standard_units(table[y]))
print('r from correlation():', round(correlation(stores, 'ad_spend', 'sales'), 3))
print('r from np.corrcoef():', round(np.corrcoef(stores['ad_spend'], stores['sales'])[0, 1], 3))
r from correlation(): 0.689
r from np.corrcoef(): 0.689
NumPy’s np.corrcoef gives the same answer. It returns a small table of correlations for every pair of its inputs, so take the entry [0, 1] to get r for the two arrays. This book keeps using its own correlation function so the definition stays visible.
Business reading: an r of about 0.69 says that advertising spending and sales are positively and fairly strongly associated across these 40 stores. It does not say yet that advertising causes the extra sales. This section returns to that below.
### Exercise: Measure a Linear Pattern
# Weekly advertising spending (thousands of dollars) and sales (thousands of dollars) for five stores.
# 1. Compute the correlation r with np.corrcoef(x, y)[0, 1]
# (np.corrcoef returns a 2 x 2 table of correlations; r is the entry [0, 1]), rounded to 3 decimals.
# 2. Print 'positive' if r is above 0 and 'negative' if it is below 0.
# Print exactly:
# r: 0.996
# Direction: positive
import numpy as np
ad_spend = np.array([1, 2, 3, 4, 5])
sales = np.array([52, 57, 60, 66, 70])
### Your code starts here.
### Your code ends here.
r: 0.996
Direction: positive
### Exercise: Which Store Trait Tracks Sales?
# The stores table has two more numeric columns: staff and store_age.
# 1. Use the correlation function to compute r between staff and sales.
# 2. Compute r between store_age and sales.
# 3. Print both values, rounded to 3 decimals.
# Print exactly:
# r (staff, sales): <value>
# r (store_age, sales): <value>
ex_stores = pd.read_csv(path_data + 'store_ad_sales.csv')
### Your code starts here.
### Your code ends here.
r (staff, sales): 0.492
r (store_age, sales): -0.133
12.1.3. Properties of r#
The way r is built gives it a handful of properties. Knowing them lets you read a correlation without recomputing anything.
r is between -1 and 1. It equals 1 only when all the dots lie exactly on a line sloping up, and -1 only when they lie exactly on a line sloping down. Most real data sets fall somewhere in between, but data with an exact linear rule, such as revenue and units sold at a fixed price, do reach 1.
r has no units. Because both variables are converted to standard units before the products are averaged, the units cancel. A correlation of 0.69 is not “0.69 thousand dollars” or “0.69 per dollar”. It is a pure number.
r does not change when you change units. Converting advertising spending from thousands of dollars to dollars, or sales from thousands to millions, multiplies the values by a positive constant. Standard units are unaffected by this, so r is unaffected too. Multiplying by a negative constant flips the sign of r. The cell below checks it.
in_dollars = pd.DataFrame({
'ad_spend': stores['ad_spend'] * 1000,
'sales': stores['sales'] * 1000,
})
print('r with values in $1,000s:', round(correlation(stores, 'ad_spend', 'sales'), 3))
print('r with values in dollars: ', round(correlation(in_dollars, 'ad_spend', 'sales'), 3))
r with values in $1,000s: 0.689
r with values in dollars: 0.689
r is symmetric. The mean of the products is the same whichever variable you call x, so the correlation of advertising spending with sales equals the correlation of sales with advertising spending.
print('r (ad_spend, sales):', round(correlation(stores, 'ad_spend', 'sales'), 3))
print('r (sales, ad_spend):', round(correlation(stores, 'sales', 'ad_spend'), 3))
r (ad_spend, sales): 0.689
r (sales, ad_spend): 0.689
The sign shows the direction. A positive r means the variables tend to rise together. A negative r means one tends to fall as the other rises. A sales team would expect a negative r between a product’s price and its weekly units sold: the more it costs, the fewer people buy.
Only the strength depends on the size of r. An r of -0.9 is just as strong as an r of 0.9. They differ in direction, not in how tightly the dots follow a line.
Words such as weak, moderate, and strong are judgment calls, not fixed cutoffs. An r of 0.5 is high for survey data about people and low for a calibrated instrument.
Business reading: because r has no units and ignores the scale of measurement, a manager can compare the strength of association across very different pairs, such as advertising spending and sales, or price and units sold, without worrying about dollars versus thousands.
### Exercise: Changing Units
# Weekly sales for 40 stores are in $1,000s. A finance team prefers sales in dollars,
# and wants advertising spending as the y variable instead of the x variable.
# 1. Convert sales to dollars by multiplying by 1000.
# 2. Compute r for (ad_spend, sales in thousands).
# 3. Compute r for (sales in dollars, ad_spend): sales as x, advertising spending as y.
# 4. Print both rounded to 3 decimals, then print whether they are equal when rounded.
# Print exactly:
# r (thousands): <value>
# r (dollars, swapped): <value>
# Same? True
ex_stores = pd.read_csv(path_data + 'store_ad_sales.csv')
### Your code starts here.
### Your code ends here.
r (thousands): 0.689
r (dollars, swapped): 0.689
Same? True
12.1.4. What r Does Not Measure#
A correlation is a useful summary, but it is easy to read too much into it. This part covers five cases where r is misleading or does not say what people hope it says.
12.1.4.1. Correlation Is Not Causation#
A high r says two variables move together. It does not say that one causes the other. Here is a case where the two variables clearly do not cause each other.
A seaside shop sells both ice cream and sunscreen. The data below are 36 months of simulated sales (in $1,000s) for each product. Both depend on how warm the month is, and neither depends on the other.
rng = np.random.default_rng(1202)
month = np.arange(36)
temperature = 60 + 25 * np.sin(2 * np.pi * (month - 3) / 12) + rng.normal(0, 3, 36)
ice_cream = np.round(50 + 1.5 * (temperature - 60) + rng.normal(0, 6, 36), 1)
sunscreen = np.round(35 + 0.9 * (temperature - 60) + rng.normal(0, 4, 36), 1)
shop = pd.DataFrame({'temperature': temperature, 'ice_cream': ice_cream, 'sunscreen': sunscreen})
fig, ax = plt.subplots(figsize=(6, 4))
ax.scatter(shop['ice_cream'], shop['sunscreen'], s=30)
ax.set_xlabel('Monthly ice cream sales ($1,000s)')
ax.set_ylabel('Monthly sunscreen sales ($1,000s)')
ax.set_title('Ice cream and sunscreen sales rise together')
plt.show()
print('r (ice cream, sunscreen):', round(correlation(shop, 'ice_cream', 'sunscreen'), 3))
r (ice cream, sunscreen): 0.933
The correlation is very high, about 0.93, yet nobody believes that selling ice cream makes customers buy sunscreen. The pair is a spurious correlation. The explanation is a third variable, the confounder: temperature. Hot months bring both beach visitors who want ice cream and beach visitors who need sunscreen. The next cell shows each product’s link to temperature.
print(f"r (temperature, ice cream): {correlation(shop, 'temperature', 'ice_cream'):.3f}")
print(f"r (temperature, sunscreen): {correlation(shop, 'temperature', 'sunscreen'):.3f}")
similar = shop[(shop['temperature'] > 68) & (shop['temperature'] < 78)]
print('Months with temperature between 68 and 78:', len(similar))
print(f"r (ice cream, sunscreen) in those months: {correlation(similar, 'ice_cream', 'sunscreen'):.3f}")
r (temperature, ice cream): 0.978
r (temperature, sunscreen): 0.970
Months with temperature between 68 and 78: 7
r (ice cream, sunscreen) in those months: 0.058
Both products are strongly tied to temperature. When you look only at months with similar temperatures, the link between ice cream and sunscreen nearly disappears: r drops to about 0.06 across just 7 months (a small sample, so treat that number loosely). Holding the confounder roughly fixed removes most of the association.
The same trap appears with real business data. Stores that advertise more may also be larger, in bigger markets, or in better locations, and any of these could raise sales on its own. This is the confounding problem you met in Comparing Groups Without Random Assignment. With observational data like the 40 stores, r describes how the variables move together. An experiment that randomly assigns ad budgets to stores is the most direct way to estimate whether ads cause sales.
### Exercise: Correlation and a Third Variable
# Five summer weeks: temperature (F), ice cream sales (units), and swimming accidents.
# 1. Compute r between ice cream sales and accidents, rounded to 2 decimals.
# 2. Compute r between temperature and each of the other two columns.
# 3. Check whether temperature has an r above 0.9 with both ice cream and
# accidents. If so, temperature is a likely third variable behind step 1.
# Print exactly:
# Ice cream vs accidents: 0.99
# Temperature vs ice cream: 0.99
# Temperature vs accidents: 0.99
# Temperature tracks both: True
import numpy as np
temperature = np.array([70, 75, 80, 85, 90])
ice_cream = np.array([200, 260, 340, 450, 560])
accidents = np.array([2, 3, 4, 6, 7])
### Your code starts here.
### Your code ends here.
Ice cream vs accidents: 0.99
Temperature vs ice cream: 0.99
Temperature vs accidents: 0.99
Temperature tracks both: True
12.1.4.2. Only Linear Association#
The correlation coefficient measures how well a straight line describes the dots. A strong relationship that is not a straight line can still produce a high r, and a very strong curved one can produce a low r.
The file price_demand.csv holds 104 weeks of price and units sold for one product. These data are simulated, built so that demand falls along a curve.
weeks = pd.read_csv(path_data + 'price_demand.csv')
fig, ax = plt.subplots(figsize=(6, 4))
ax.scatter(weeks['price'], weeks['units'], s=25)
ax.set_xlabel('Price ($)')
ax.set_ylabel('Units sold per week')
ax.set_title('Demand falls with price, but along a curve')
plt.show()
print('r (price, units):', round(correlation(weeks, 'price', 'units'), 3))
r (price, units): -0.951
The r is about -0.95, which says the relationship is strong and negative. That is true, but r hides the shape. The dots do not follow a straight line: demand drops quickly at low prices and more slowly at high ones. The table below averages units sold within price bands to show it.
weeks['price_band'] = pd.cut(weeks['price'], bins=[4, 7, 10, 13, 16])
weeks.groupby('price_band', observed=True)['units'].mean().round(1)
price_band
(4, 7] 329.2
(7, 10] 193.0
(10, 13] 113.9
(13, 16] 63.4
Name: units, dtype: float64
Moving from the cheapest band to the next band costs about 136 units a week, but moving from the third band to the most expensive costs only about 50. A straight line would claim the same drop for each step. A single r cannot describe that. Always look at the scatter plot before you trust a correlation, and do not read a high r as proof that a line fits. The section Diagnostics and Inference shows how to check this with residual plots.
The opposite mistake is also possible: a strong relationship with an r near 0. Profit often rises with price up to a point and then falls, because higher prices drive customers away. The next cell simulates 50 weeks of profit at prices from $4 to $16 for one product, built so that profit peaks at a price of $10.
rng = np.random.default_rng(1204)
price = np.linspace(4, 16, 50)
profit = 2000 - 40 * (price - 10) ** 2 + rng.normal(0, 100, 50)
profit_weeks = pd.DataFrame({'price': price, 'profit': profit})
fig, ax = plt.subplots(figsize=(6, 4))
ax.scatter(profit_weeks['price'], profit_weeks['profit'], s=25)
ax.set_xlabel('Price ($)')
ax.set_ylabel('Weekly profit ($)')
ax.set_title('Profit peaks at a middle price')
plt.show()
print('r (price, profit):', round(correlation(profit_weeks, 'price', 'profit'), 3))
r (price, profit): -0.022
The r is about 0, yet price clearly matters: profit is highest near $10 and falls off on both sides. The positive products on one side of the peak cancel the negative products on the other. An r near 0 means no straight-line association, not no relationship.
### Exercise: A Curve and a Line
# The price_demand.csv file holds weekly price and units sold. Demand falls along a curve.
# Taking the logarithm of units straightens the curve.
# 1. Load the data. Compute r between price and units.
# 2. Add a column log_units = np.log(units) and compute r between price and log_units.
# 3. Print both, rounded to 3 decimals.
# 4. Draw a scatter plot of log_units against price. Is the pattern closer to a straight line?
# Print exactly:
# r (price, units): <value>
# r (price, log units): <value>
ex_weeks = pd.read_csv(path_data + 'price_demand.csv')
### Your code starts here.
### Your code ends here.
r (price, units): -0.951
r (price, log units): -0.968
12.1.4.3. Outliers#
An outlier is a point far from the rest. Because r averages products of standard units, one extreme point can change it a lot. Suppose (an invented example) a new store opened this year, spent heavily on ads to build awareness, and has not yet built a customer base. Add that store to the 40 and recompute r.
new_store = pd.DataFrame({'store': ['S41'], 'region': ['North'], 'ad_spend': [9.5],
'staff': [10], 'store_age': [0], 'sales': [40.0]})
with_new = pd.concat([stores, new_store], ignore_index=True)
fig, axes = plt.subplots(1, 2, figsize=(10, 3.8), sharey=True)
for ax, data, title in zip(axes, [stores, with_new], ['40 stores', '40 stores plus one new store']):
ax.scatter(data['ad_spend'], data['sales'], s=30)
ax.set_xlabel('Weekly advertising spending ($1,000s)')
ax.set_title(title + ': r = ' + str(round(correlation(data, 'ad_spend', 'sales'), 2)), fontsize=11)
axes[0].set_ylabel('Weekly sales ($1,000s)')
axes[1].scatter([9.5], [40.0], s=60, color='red')
plt.show()
print('r without the new store:', round(correlation(stores, 'ad_spend', 'sales'), 3))
print('r with the new store: ', round(correlation(with_new, 'ad_spend', 'sales'), 3))
r without the new store: 0.689
r with the new store: 0.542
One store out of 41 pulls r from about 0.69 down to about 0.54. That store is not an error; it is a valid observation with a story worth investigating. The lesson is to plot the data first, find the unusual points, and ask what explains them. Then report r with and without the point, or explain why it should be excluded.
12.1.4.4. Anscombe’s Quartet#
In 1973 the statistician F. J. Anscombe published four small data sets, each with 11 pairs of x and y values, that he constructed to make one point about summaries. They are not measurements of anything real, and they were not simulated for this book: they are the famous values printed in his paper “Graphs in Statistical Analysis” (The American Statistician, 1973). Look first at the summary numbers for each data set.
quartet = pd.read_csv(path_data + 'anscombe_quartet.csv')
rows = []
for name in ['I', 'II', 'III', 'IV']:
d = quartet[quartet['dataset'] == name]
rows.append({'dataset': name,
'mean_x': np.mean(d['x']), 'mean_y': np.mean(d['y']),
'sd_x': np.std(d['x']), 'sd_y': np.std(d['y']),
'r': correlation(d, 'x', 'y')})
pd.DataFrame(rows).round(3)
| dataset | mean_x | mean_y | sd_x | sd_y | r | |
|---|---|---|---|---|---|---|
| 0 | I | 9.0 | 7.501 | 3.162 | 1.937 | 0.816 |
| 1 | II | 9.0 | 7.501 | 3.162 | 1.937 | 0.816 |
| 2 | III | 9.0 | 7.500 | 3.162 | 1.936 | 0.816 |
| 3 | IV | 9.0 | 7.501 | 3.162 | 1.936 | 0.817 |
The four data sets have almost the same mean of x, mean of y, standard deviations, and r of about 0.816. Their best-fitting lines are also nearly the same, about y = 3 + 0.5x (the line is the subject of Regression Line). If you looked only at these numbers you would say the four data sets are the same. Now plot them.
fig, axes = plt.subplots(2, 2, figsize=(7, 5.5), sharex=True, sharey=True)
for ax, name in zip(axes.flat, ['I', 'II', 'III', 'IV']):
d = quartet[quartet['dataset'] == name]
ax.scatter(d['x'], d['y'], s=30)
ax.set_title('Data set ' + name + ': r = ' + str(round(correlation(d, 'x', 'y'), 3)), fontsize=11)
for ax in axes[1]:
ax.set_xlabel('x')
for ax in axes[:, 0]:
ax.set_ylabel('y')
plt.show()
The pictures could hardly differ more. Data set I is a straight-line pattern with ordinary scatter. Data set II is a smooth curve, so r misdescribes it. Data set III is an almost perfect line with a single outlier that pulls r down. In data set IV every x value is 8 except one, and that one point alone creates the whole correlation.
Lesson: r cannot tell a straight-line pattern from a curve, a line with one outlier, or a single influential point. Always plot the data before you trust a correlation. The section Diagnostics and Inference returns to the quartet and shows how residual plots reveal what r hides.
12.1.4.5. Aggregated Data#
Data are often reported as averages for groups, such as regions, instead of one row per store. The correlation of group averages is often much stronger than the correlation of individuals, because averaging smooths out the individual noise. This is called an ecological correlation.
To see this, simulate a chain with 10 regions and 30 stores per region. In every region, stores differ a great deal in advertising spending and sales, and the link between the two inside a region is weak on average. But regions with higher typical ad budgets also have higher typical sales.
rng = np.random.default_rng(1203)
region_centers = np.linspace(4, 11, 10)
rows = []
for k, center in enumerate(region_centers):
ad = center + rng.normal(0, 1.5, 30)
sales = 30 + 3 * center + 0.5 * (ad - center) + rng.normal(0, 9, 30)
for a, s in zip(ad, sales):
rows.append((k + 1, a, s))
many = pd.DataFrame(rows, columns=['region', 'ad_spend', 'sales'])
region_avg = many.groupby('region').mean()
fig, axes = plt.subplots(1, 2, figsize=(10, 3.8))
axes[0].scatter(many['ad_spend'], many['sales'], c=many['region'], cmap='tab10', s=12)
axes[0].set_title('300 individual stores (color = region)', fontsize=11)
axes[1].scatter(region_avg['ad_spend'], region_avg['sales'], s=40, color='darkorange')
axes[1].set_title('10 region averages', fontsize=11)
for ax in axes:
ax.set_xlabel('Weekly advertising spending ($1,000s)')
ax.set_ylabel('Weekly sales ($1,000s)')
plt.show()
within = [correlation(group, 'ad_spend', 'sales') for _, group in many.groupby('region')]
print('Average r within a region:', round(np.mean(within), 3))
print('r for 300 stores: ', round(correlation(many, 'ad_spend', 'sales'), 3))
print('r for 10 region averages:', round(correlation(region_avg, 'ad_spend', 'sales'), 3))
Average r within a region: 0.199
r for 300 stores: 0.598
r for 10 region averages: 0.977
Across the 300 stores r is about 0.60. Across the 10 region averages it is about 0.98. The averages line up almost perfectly because the noise within each region has been averaged away.
In this simulation the gap has two sources. Averaging removes store-to-store noise, which tightens the cloud. The regions also differ for reasons of their own: sales rise about $3,000 for each extra $1,000 in a region’s typical ad budget, but only about $500 for each extra $1,000 a store spends above its region’s typical level. A line fitted to region averages therefore describes how regions differ, not what happens when one store spends more.
The danger is in the interpretation. A report that shows only region averages invites the conclusion that, for any one store, more advertising spending reliably brings more sales. The individual stores say otherwise: inside a region, the dots of one color are widely scattered, and the within-region r averages only about 0.20 (it varies from region to region, as any r from 30 points does). Region averages describe regions. Do not use them to predict or judge a single store.
### Exercise: Stores vs. Region Averages
# Twelve stores in three regions: weekly advertising spending and sales ($1,000s).
# 1. Compute r for the 12 individual stores with the correlation function.
# 2. Average ad_spend and sales by region with groupby('region').mean().
# 3. Compute r for the 3 region averages.
# 4. Print both, rounded to 3 decimals.
# Print exactly:
# r for 12 stores: 0.639
# r for 3 region averages: 0.987
ex_chain = pd.DataFrame({
'region': ['A'] * 4 + ['B'] * 4 + ['C'] * 4,
'ad_spend': [2, 3, 4, 5, 4, 5, 6, 7, 6, 7, 8, 9],
'sales': [58, 44, 52, 46, 60, 74, 58, 68, 80, 66, 76, 72],
})
### Your code starts here.
### Your code ends here.
r for 12 stores: 0.639
r for 3 region averages: 0.987
12.1.5. Section Practice#
### Exercise: Practice Correlation
# A coffee chain recorded daily temperature (F) and iced-drink sales at one store.
# 1. Convert both variables to standard units (np.mean, np.std).
# 2. Compute r as the mean of the products of the standard units.
# 3. Check your answer with np.corrcoef(x, y)[0, 1]. Print both, rounded to 3 decimals.
# Print exactly:
# r: 0.985
# np.corrcoef: 0.985
import numpy as np
temperature = np.array([58, 62, 66, 70, 75, 79, 83, 88])
iced_sales = np.array([120, 135, 150, 148, 180, 205, 210, 240])
### Your code starts here.
### Your code ends here.
r: 0.985
np.corrcoef: 0.985