11.2. The Bootstrap#

Hide code cell source

path_data = '../../data/'

import numpy as np
import pandas as pd

import matplotlib.pyplot as plt
from matplotlib.patches import FancyBboxPatch, FancyArrowPatch
%matplotlib inline

plt.rcParams['figure.facecolor'] = 'white'
plt.rcParams['axes.facecolor'] = 'white'
plt.rcParams['axes.spines.top'] = False
plt.rcParams['axes.spines.right'] = False
plt.rcParams['font.size'] = 11

The previous section described a data set. In practice, you rarely have the whole population: you have a sample, and you want to say something about the population it came from. A statistic computed from a sample, such as a median, is only an estimate of the matching population parameter, and a different sample would give a different estimate. How far off might the estimate be?

The section on sampling variability answered that question by drawing many samples from a known population. Real analysts do not get to do that: they have one sample and no way to go back to the population. This section introduces the bootstrap, a method that uses the one available sample to approximate how much an estimate would vary from sample to sample. Its first steps are the same as in that section; the key move comes in Resampling from the Sample.

11.2.1. Estimating Median Pay#

A budget analyst for the State of Missouri wants to report the median annual pay of state employees. In real work the analyst would look at a sample of employee records, perhaps a few hundred, because pulling every record is slow or restricted. The question is how close the sample median is to the median of all employees.

To check the method, you need a case where the answer is known. So this section treats a large extract of the state’s payroll as the whole population, draws a sample from it as the analyst would, and then compares the estimate with the true value.

The file missouri_state_pay_2025.csv is a random extract of 20,000 employees from the State of Missouri’s public 2025 State Employee Pay data (data.mo.gov ). The pay, agency, and position title in each row are real. The employee names are made up: they were generated at random and do not belong to the people whose pay is shown. This section never uses the names.

The column gross_pay_2025 is gross pay the employee received in calendar year 2025, in dollars. It is a total for the year, not a salary rate, so an employee who worked only part of the year shows a smaller amount.

df = pd.read_csv(path_data + 'missouri_state_pay_2025.csv')
print(df.shape)
print(df.columns.tolist())

# Quartiles and averages only: the minimum and maximum would each be one person's pay
print(df['gross_pay_2025'].describe().drop(['min', 'max']).round(2))

print("\n", df)
print(df.head().to_string())
(20000, 4)
['employee_name', 'agency_name', 'position_title', 'gross_pay_2025']
count    20000.00
mean     39594.37
std      33325.63
25%      13061.45
50%      39066.21
75%      55558.98
Name: gross_pay_2025, dtype: float64

                  employee_name                 agency_name  \
0              RUSSELL, PHILIP               PUBLIC SAFETY   
1                 RUIZ, EUGENE                 CORRECTIONS   
2                 HENRY, GRACE                   JUDICIARY   
3               PENA, SCOTT C.  HEALTH AND SENIOR SERVICES   
4                BELL, GARY R.              TRANSPORTATION   
...                        ...                         ...   
19995        HOLMES, GEORGE C.                 AGRICULTURE   
19996         ALEXANDER, PETER             SOCIAL SERVICES   
19997  ROBERTSON, STEPHANIE E.              NATIONAL GUARD   
19998          NGUYEN, EMMA M.                   JUDICIARY   
19999           JAMES, ALAN W.               PUBLIC SAFETY   

                     position_title  gross_pay_2025  
0            SUPPORT CARE ASSISTANT        29550.93  
1             CORRECTIONAL SERGEANT        94841.84  
2                       COURT CLERK        41571.70  
3       SOCIAL SVCS UNIT SUPERVISOR        58886.92  
4      SR INFO SYSTEMS TECHNOLOGIST        22970.04  
...                             ...             ...  
19995            FAIR WEEK EMPLOYEE         1252.50  
19996  LEAD ADMIN SUPPORT ASSISTANT        40709.06  
19997     SENIOR ACCOUNTS ASSISTANT        46105.58  
19998                  INVESTIGATOR        55063.32  
19999           FOOD SERVICE WORKER        43257.30  

[20000 rows x 4 columns]
     employee_name                 agency_name                position_title  gross_pay_2025
0  RUSSELL, PHILIP               PUBLIC SAFETY        SUPPORT CARE ASSISTANT        29550.93
1     RUIZ, EUGENE                 CORRECTIONS         CORRECTIONAL SERGEANT        94841.84
2     HENRY, GRACE                   JUDICIARY                   COURT CLERK        41571.70
3   PENA, SCOTT C.  HEALTH AND SENIOR SERVICES   SOCIAL SVCS UNIT SUPERVISOR        58886.92
4    BELL, GARY R.              TRANSPORTATION  SR INFO SYSTEMS TECHNOLOGIST        22970.04

Each row is one employee, with 20,000 rows in all, and four columns: a made-up name, the agency, the position title, and 2025 gross pay. The pay records belong to real people, so this section works with summaries such as the one above instead of displaying individual rows. The data include 25 agencies. The table below lists the five with the most employees in the extract.

by_agency = df.groupby('agency_name')['gross_pay_2025'].agg(['count', 'median'])
by_agency = by_agency.sort_values(by='count', ascending=False)
by_agency.head(5)
count median
agency_name
CORRECTIONS 3639 37841.030
MENTAL HEALTH 2893 37187.770
SOCIAL SERVICES 2346 39066.230
TRANSPORTATION 1960 42105.035
PUBLIC SAFETY 1940 37910.375

The five agencies with the most employees in the extract are shown above, along with each agency’s median pay. Agencies differ a lot, which is one reason pay across the state is spread out. This section summarizes the whole group with one number, the median.

11.2.2. Population and Parameter#

An estimate always refers to a specific group, so you have to say which group before you calculate anything. Look at the smallest pay amounts in the file.

pay = df['gross_pay_2025']

under_15k = (pay < 15000).sum()
negative = (pay < 0).sum()

print('Employees in the extract:', len(df))
print('Paid under $15,000:', under_15k, 
      '(' + str(round(100 * under_15k / len(df), 1)) + '%)')
print('Of those, negative pay:', negative)
Employees in the extract: 20000
Paid under $15,000: 5418 (27.1%)
Of those, negative pay: 21

Many employees received under $15,000 in 2025. Most of them probably worked only part of the year or part time: they joined or left during 2025, or work a few hours a week. A few rows are negative, which come from payroll corrections, not from pay for work. Gross pay for these employees says little about what a regular position pays.

To make a more comparable group, keep employees paid at least $15,000. This is a screen on the pay column, not a direct measure of hours worked, and it changes the group the answer applies to. The analysis population is state employees paid at least $15,000 in 2025.

population = df[df['gross_pay_2025'] >= 15000].reset_index(drop=True)
pop_pay = population['gross_pay_2025']

print('Employees in the extract:', len(df))
print('Rows removed:', len(df) - len(population))
print('Analysis population:', len(population))
Employees in the extract: 20000
Rows removed: 5418
Analysis population: 14582

The filter removes 5,418 rows, leaving 14,582 employees. From here on, these 14,582 employees are the population. The parameter to estimate is the median gross pay of this group. The histogram shows the pay of the individual employees in it.

fig, ax = plt.subplots(figsize=(7, 3.8))

ax.hist(pop_pay, bins=np.arange(15000, 200001, 5000), color='#4c78a8',
        edgecolor='white')

ax.set_xlabel('Gross pay in 2025 (dollars)')
ax.set_ylabel('Number of employees')
ax.set_title('Most of the analysis population is paid under $80,000; a few are paid far more')
ax.set_xlim(0, 200000)
plt.show()

print('Employees paid more than $200,000 (not shown):', (pop_pay > 200000).sum())
../../_images/06fa6a6c2720689d55265151a4f27fcda68839900759b4092b7b679993936bc8.png
Employees paid more than $200,000 (not shown): 15
print('Population median (the parameter):', round(pop_pay.median(), 2))
print('Population mean:', round(pop_pay.mean(), 2))
Population median (the parameter): 47864.46
Population mean: 52114.8

The median gross pay in the analysis population is $47,864. This is the number a sample will try to estimate. The mean is $52,115, higher than the median because a long tail of high pay pulls the mean up. For skewed values like pay, the median is the better description of a typical employee, so the median is the parameter chosen here.

The median of all 20,000 rows is $39,066. It is a different parameter because it describes a different group, one that includes part-year and part-time staff. (By coincidence, it is within a cent of the Social Services median in the agency table above; the two are computed from different rows.)

The population median is known here only so that you can check how well the bootstrap estimation works. In real work, that value would usually be unknown. The bootstrap uses only the sampled employees, just as it would if the population median were unknown.

11.2.2.1. Practice#

### Exercise: Filter the Analysis Population
# Pay amounts (in dollars) for eight employees are in pay_small.
#   1. Keep only the employees paid at least 15,000.
#   2. Print how many were kept, how many were removed, and the median of those kept.
# Print exactly:
# Kept: 5
# Removed: 3
# Median of kept: 41000.0
import pandas as pd
pay_small = pd.Series([-250, 4200, 9800, 15000, 28000, 41000, 52000, 90000])
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
import pandas as pd
pay_small = pd.Series([-250, 4200, 9800, 15000, 28000, 41000, 52000, 90000])
kept = pay_small[pay_small >= 15000]
print('Kept:', len(kept))
print('Removed:', len(pay_small) - len(kept))
print('Median of kept:', kept.median())
Kept: 5
Removed: 3
Median of kept: 41000.0

11.2.3. A Random Sample and an Estimate#

Now play the analyst. Draw a random sample of 300 employees from the population, without replacement, so no employee appears twice. The seeded generator makes the draw repeatable.

rng = np.random.default_rng(2025)

# choice(): ch0303 & 1001; positions here.
chosen = rng.choice(len(population), size=300, replace=False)

sample = population.iloc[chosen]		### size: 300
sample_pay = sample['gross_pay_2025']

# print(type(sample_pay))
print('Sample size:', len(sample_pay))
print('Sample median:', round(np.median(sample_pay), 2))
Sample size: 300
Sample median: 47454.06

The sample median, $47,454, is the point estimate: a single number used to estimate the parameter. The estimate differs from the true median of $47,864 by $410. The true value is known only because this section built the population. A real analyst would not, and would want to know how large such a gap could be.

A different random sample of 300 would give a different median, so the estimate has sampling variability. If you could draw thousands of samples from the population, you could see how widely the medians spread, as in the sampling variability section. But the analyst has one sample and no access to the population. The bootstrap supplies a substitute.

11.2.4. Resampling from the Sample#

The idea of the bootstrap is to use the sample as a small stand-in for the population. You cannot sample from the population again, but you can sample from the sample. Each such draw is called a resample: a new sample of the same size as the original, taken from the original sample with replacement. With replacement means each draw is put back before the next one, so a resample can contain the same employee several times and leave others out.

The figure shows the full process. The first arrow is the real sampling that the analyst did once. The second arrow is the resampling, which can be repeated as many times as you like at no cost.

fig, ax = plt.subplots(figsize=(8, 3.6))
ax.set_xlim(0, 10); ax.set_ylim(-0.3, 4.2); ax.axis('off')

def box(x, y, w, h, text, color):
    ax.add_patch(FancyBboxPatch((x, y), w, h, boxstyle='round,pad=0.05',
                                facecolor=color, edgecolor='#333333', linewidth=1.2)
                )
    ax.text(x + w / 2, y + h / 2, text, ha='center', va='center', fontsize=10)

def arrow(x0, y0, x1, y1):
    ax.add_patch(FancyArrowPatch((x0, y0), (x1, y1), arrowstyle='-|>',
                                 mutation_scale=16, color='#333333', linewidth=1.5))

box(0.2, 1.3, 2.4, 1.6, 'Population\n14,582 employees\nparameter: median', '#dbe7f3')
box(3.9, 1.3, 2.2, 1.6, 'One sample\n300 employees\nsample median', '#fbe3c2')
for i, y in enumerate([2.9, 1.9, 0.9, 0.0]):
    label = 'Resample %d: median' % (i + 1) if i < 3 else '... and so on'
    box(7.4, y - 0.1 + (0.1 if i < 3 else 0), 2.4, 0.7, label, '#dff0d8' if i < 3 else 'white')
    
arrow(2.7, 2.1, 3.8, 2.1)
arrow(6.2, 2.1, 7.3, 3.2)
arrow(6.2, 2.1, 7.3, 2.2)
arrow(6.2, 2.1, 7.3, 1.2)
ax.text(3.25, 2.4, 'draw 300\nwithout\nreplacement', ha='center', va='bottom', fontsize=9)
ax.text(6.2, 0.55, 'draw 300 with\nreplacement, many times', ha='center', va='top', fontsize=9)
ax.set_title('The bootstrap resamples the one available sample')
plt.show()
../../_images/572923a21df46eba19a83bcd6da4b94f0f8067a4909481003beb940eb43fb1d4.png

The values in the original sample form an empirical distribution: the distribution of the observed data. Every resample is drawn from this empirical distribution, not from the population.

Keep three distributions separate, because they are easy to confuse:

Distribution

What varies?

What it describes

Individual observations

The pay of each employee.

Variation in employee pay.

Sampling distribution

A statistic from each new sample of the population.

How an estimate varies across repeated samples.

Bootstrap distribution

A statistic from each resample of one fixed sample.

An approximation to that sampling variability.

The original sample size is n (here 300) and the number of resamples is B. A larger n gives more information about the population. A larger B only makes the picture of the bootstrap distribution smoother; it adds no information about the population.

11.2.4.1. One Resample#

To perform a bootstrap resample, use rng.choice() to draw with replacement from the sample. This resample uses a NumPy generator, rng. rng.choice(sample_pay, size=len(sample_pay), replace=True) draws 300 values from the sample, putting each back after it is drawn.

boot_rng = np.random.default_rng(7)
resample = boot_rng.choice(sample_pay, size=len(sample_pay), replace=True)

print('Original sample size:', len(sample_pay))
print('Resample size:', len(resample))
print('Distinct employees in the resample:', len(np.unique(resample)))
print('Sample median:', round(np.median(sample_pay), 2))
print('Resample median:', round(np.median(resample), 2))
Original sample size: 300
Resample size: 300
Distinct employees in the resample: 191
Sample median: 47454.06
Resample median: 46452.75

The resample has the same size as the original, but only 191 of the 300 employees appear in it, because some were drawn more than once and others not at all. (Every employee in this sample has a different pay amount, so counting distinct amounts counts distinct employees.) Its median, $46,453, differs from the sample median of $47,454. That difference is the kind of variation you want to measure.

If the data are in a DataFrame, the .sample() method does the same job. frac=1 asks for 100% of the rows, so the resample has the same size as the table, and replace=True puts each row back after it is drawn. The random_state argument fixes the draw.

resample_df = sample.sample(frac=1, replace=True,
                            random_state=7)

print('Rows in the resample:', len(resample_df))
print('Median pay in the resample:', round(resample_df['gross_pay_2025'].median(), 2))
Rows in the resample: 300
Median pay in the resample: 46825.24

The two methods give slightly different resamples, because they use different random number streams, but both are valid and both resample the sample with replacement. Use .sample() when you want to keep the other columns, such as agency; use rng.choice when you only need the values.

11.2.4.2. Many Resamples#

One resample median tells you little. The bootstrap repeats the process many times, records the median each time, and looks at how those medians spread out. Use B = 5,000 resamples. Each pass through the loop draws one resample of 300 from the sample and saves its median.

many_rng = np.random.default_rng(11)
B = 5000
boot_medians = np.zeros(B)
for i in range(B):
    resample = many_rng.choice(sample_pay, size=len(sample_pay), replace=True)
    boot_medians[i] = np.median(resample)

print('Number of bootstrap medians:', len(boot_medians))
print('Smallest:', round(boot_medians.min(), 2))
print('Largest:', round(boot_medians.max(), 2))
print('Standard deviation of the bootstrap medians:', round(boot_medians.std(), 2))
Number of bootstrap medians: 5000
Smallest: 41617.16
Largest: 51814.59
Standard deviation of the bootstrap medians: 1409.02
fig, ax = plt.subplots(figsize=(7, 3.8))
ax.hist(boot_medians, bins=40, color='#9ecae1', edgecolor='white')
ax.axvline(pop_pay.median(), color='#2ca02c', linewidth=2.5, label='Population median (parameter)')
ax.axvline(np.median(sample_pay), color='#d62728', linewidth=2, linestyle='--', label='Sample median')
ax.set_xlabel('Median gross pay in a resample (dollars)')
ax.set_ylabel('Number of resamples')
ax.set_title('Resample medians cluster around the sample median')
ax.legend(frameon=False)
plt.show()
../../_images/3e5920fd29b6b82753d612089591bae6e4042323076068886b6f1485186f24bd.png
print('Center of the bootstrap medians (their mean):', round(boot_medians.mean(), 2))
print('Sample median:', round(np.median(sample_pay), 2))
print('Population median:', round(pop_pay.median(), 2))
Center of the bootstrap medians (their mean): 47325.17
Sample median: 47454.06
Population median: 47864.46

The bootstrap medians are centered near the sample median, not near the parameter. That makes sense: the resamples come from the sample, so they know only what the sample knows. What the histogram gives you is the spread. The standard deviation of the 5,000 medians, about $1,409, is the bootstrap’s estimate of how far a sample median typically lies from the median it is estimating. That quantity is the standard error of the median, the same idea as in Sampling Variability; the bootstrap estimates it without a formula.

Resampling makes the sample play the role of the population. For a statistic like the median, in a sample that is large and representative, the spread of resample medians approximates the spread of medians across real samples. It is an approximation under conditions, not a guarantee. The sample is 2.1% of the population, small enough that sampling with replacement from the sample is a close stand-in for the without-replacement sampling that produced it. The bootstrap cannot repair bias, a systematic error such as a sample that overrepresents some groups. It cannot bring back groups that were left out or discover values larger than any in the sample. More resamples do not fix those problems.

The point estimate does not have to equal the parameter, and here it does not. The next section asks whether the bootstrap distribution lets you make a statement about the parameter that is right most of the time.

11.2.4.3. Practice#

11.2.4.3.1. Resample the Same Size#

### Exercise: Resample the Same Size
# Draw a bootstrap resample with replacement and the same size as salaries.
# Use salaries.sample(..., replace=True, random_state=1).
# Print the original and resample sizes, then the number of distinct resampled values.
# Print exactly:
# Original size: 10
# Resample size: 10
# Distinct resampled values: 7
import pandas as pd
salaries = pd.Series([58, 62, 64, 66, 70, 72, 75, 81, 88, 120])
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
import pandas as pd
salaries = pd.Series([58, 62, 64, 66, 70, 72, 75, 81, 88, 120])
resample = salaries.sample(len(salaries), replace=True, random_state=1)
print('Original size:', len(salaries))
print('Resample size:', len(resample))
print('Distinct resampled values:', resample.nunique())
# Sampling without replacement at the same size would only reorder the sample.
Original size: 10
Resample size: 10
Distinct resampled values: 7

11.2.4.3.2. Collect Bootstrap Statistics#

### Exercise: Collect Bootstrap Statistics
# Use a single seeded generator to make 100 resamples and collect their medians.
# Each resample must have size len(values).
# Print how many statistics were collected, then the smallest and largest median.
# Print exactly:
# Bootstrap statistics: 100
# Smallest median: 63.0
# Largest median: 84.5
import numpy as np
rng = np.random.default_rng(42)
values = np.array([58, 62, 64, 66, 70, 72, 75, 81, 88, 120])
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
import numpy as np
rng = np.random.default_rng(42)
values = np.array([58, 62, 64, 66, 70, 72, 75, 81, 88, 120])
medians = []
for _ in range(100):
    resample = rng.choice(values, size=len(values), replace=True)
    medians.append(np.median(resample))
print('Bootstrap statistics:', len(medians))
print('Smallest median:', min(medians))
print('Largest median:', max(medians))
# The medians spread from 63 to 84.5, but there are still only ten original
# observations, despite the 100 resamples.
Bootstrap statistics: 100
Smallest median: 63.0
Largest median: 84.5

11.2.5. Do the Estimates Capture the Parameter?#

Instead of reporting one number, the analyst can report a range of plausible values. The bootstrap percentile method builds that range from the middle 95% of the bootstrap medians: the interval’s left endpoint is their 2.5th percentile and its right endpoint is their 97.5th percentile. An interval like this is called a confidence interval, the subject of Confidence Intervals. Because the population is available here, you can check the interval.

left = np.percentile(boot_medians, 2.5, method='nearest')
right = np.percentile(boot_medians, 97.5, method='nearest')
print('95% bootstrap interval:', round(left, 2), 'to', round(right, 2))
print('Population median:', round(pop_pay.median(), 2))
print('Interval captures the parameter:', left <= pop_pay.median() <= right)
95% bootstrap interval: 44180.78 to 49819.78
Population median: 47864.46
Interval captures the parameter: True

The interval runs from $44,181 to $49,820. The population median of $47,864 lies inside it. A single interval does not tell you how reliable the method is, since any one interval may capture the parameter or miss it.

To examine the method, repeat the whole experiment: draw a new original sample from the population, bootstrap that sample, and build its interval. Do this 100 times. Each repetition uses a new sample of 300 employees and 1,000 resamples of that sample. These counts describe different operations: 100 new samples from the population, and 1,000 resamples within each. The array form rng.choice(values, size=(1000, 300)) makes a table with one resample per row, and np.median(..., axis=1) finds each row’s median, which avoids a slow inner loop.

cover_rng = np.random.default_rng(99)
n_experiments = 100
lefts = np.zeros(n_experiments)
rights = np.zeros(n_experiments)

for k in range(n_experiments):
    new_sample = cover_rng.choice(pop_pay, size=300, replace=False)
    resamples = cover_rng.choice(new_sample, size=(1000, 300), replace=True)
    medians_k = np.median(resamples, axis=1)
    lefts[k] = np.percentile(medians_k, 2.5, method='nearest')
    rights[k] = np.percentile(medians_k, 97.5, method='nearest')

true_median = pop_pay.median()
covered = (lefts <= true_median) & (true_median <= rights)
print('Intervals computed:', n_experiments)
print('Intervals that capture the population median:', covered.sum())
print('Average interval width:', round((rights - lefts).mean(), 2))
Intervals computed: 100
Intervals that capture the population median: 97
Average interval width: 5478.02

An interval covers the parameter when left <= parameter <= right. Equality at either endpoint counts as covering, which matters when values are rounded or repeated. The count above is the observed coverage in this demonstration. The plot shows each interval as a horizontal segment: blue segments cover the green line and red ones miss it. The vertical axis numbers the 100 repeated experiments; it does not index employees or resamples.

fig, ax = plt.subplots(figsize=(7, 5))
for k in range(n_experiments):
    ax.plot([lefts[k], rights[k]], [k, k], color='#1f77b4' if covered[k] else '#d62728', linewidth=1.5)
ax.axvline(true_median, color='#2ca02c', linewidth=2.5, label='Population median')
ax.set_xlabel('Median gross pay (dollars)')
ax.set_ylabel('Experiment number (new sample each time)')
ax.set_title('Most bootstrap intervals capture the population median')
ax.legend(frameon=False, loc='lower right')
plt.show()
../../_images/b443f11275e0380936bcf8fcc7fdb2718ab67e121d0099e5aaf453269c18b37d.png

97 of the 100 intervals contain the population median. The count is random and need not be exactly 95, but it should be near 95 when the method is working. The nominal 95% describes the method run over many samples, not any one interval: once you have a single interval, you do not know whether it is one of the ones that captured the parameter.

The recipe has four steps: draw a representative random sample, resample it with replacement at the same size, compute the statistic for every resample, and take the 2.5th and 97.5th percentiles of those statistics. The chapter’s next section builds on this recipe for a median, a mean, and a proportion.

11.2.5.1. Practice#

### Exercise: Include the Interval Endpoints
# Each position in left and right is one interval.
#   1. Build a True/False array: does each interval include parameter?
#      Equality at either endpoint counts.
#   2. Print how many intervals include it.
# Print exactly:
# Intervals covering the parameter: 2
import numpy as np
parameter = 10
left = np.array([8, 10, 11])
right = np.array([10, 12, 14])
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
import numpy as np
parameter = 10
left = np.array([8, 10, 11])
right = np.array([10, 12, 14])
covered_practice = (left <= parameter) & (parameter <= right)
print('Intervals covering the parameter:', np.count_nonzero(covered_practice))
Intervals covering the parameter: 2

11.2.6. Section Practice#

Use this short exercise to check the main workflow from this section. A random sample of 10 salaries (in $1,000s) is all that HR has. The next section, Confidence Intervals, names the intervals built here confidence intervals and applies them to a mean and a proportion.

### Exercise: Practice The Bootstrap
# HR has a random sample of 10 salaries (in $1,000s) in hr_sample.
#   1. Draw one bootstrap resample with hr_sample.sample(len(hr_sample), replace=True, random_state=1)
#      and compute its median.
#   2. Make 1,000 more resamples with rng.choice(hr_sample, size=len(hr_sample), replace=True)
#      and collect their medians. The seed is set once; do not reset it in the loop.
#   3. Print the sample median, the first resample's median, and the range
#      (min and max) of the 1,000 bootstrap medians.
# Print exactly:
# Sample median: 71.0
# First resample median: 73.5
# Bootstrap medians range from 62.0 to 88.0
import numpy as np
import pandas as pd
hr_sample = pd.Series([58, 62, 64, 66, 70, 72, 75, 81, 88, 120])
rng = np.random.default_rng(10)
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
import numpy as np
import pandas as pd
hr_sample = pd.Series([58, 62, 64, 66, 70, 72, 75, 81, 88, 120])
rng = np.random.default_rng(10)
first = hr_sample.sample(len(hr_sample), replace=True, random_state=1)
medians = np.array([np.median(rng.choice(hr_sample, size=len(hr_sample), replace=True))
                    for _ in range(1000)])

print('Sample median:', hr_sample.median())
print('First resample median:', first.median())
print('Bootstrap medians range from', medians.min(), 'to', medians.max())
Sample median: 71.0
First resample median: 73.5
Bootstrap medians range from 62.0 to 88.0