Skip to learning content

DATA SCIENCE PYTHON PLAYGROUND

Machine Learning · Learn / Refresh

← Clustering and Discovery lessons
Hierarchical discovery · ML-U09 · 12–18 MIN

Sampled hierarchies describe sampled rows

Keep population, sample and labels aligned.

  1. FollowRead and run the PythonCurrent exercise
  2. ChangeAdapt the Python
  3. TransferCompute and inspect the evidence

Understand the idea

Production fits the scale on the exploratory population, then transforms a reproducible sample of at most 500 rows for the hierarchy. The resulting labels belong to those sampled rows.

Illustrative data

Click the highlighted code to change the result.

sample = example.sample(, random_state=42)
Before
original rowlength_mmwidth_cm
w1101
w2111.3
w3120.7
w4256
w5266.2
w6402
w7412.4
w8421.7
Sample
original rowlength_mmwidth_cm
w2111.3
w6402
w1101
w8421.7

Sample 4 rows with seed 42, preserving their values and original indices.

What the syntax does

X.sample
  • Selects rows while preserving their original index labels.

Supplied for this practice

These objects are prepared afresh before your editor runs.

X
Feature dataframe for the declared population, preserving row indices.
X = df[['bill_length_mm', 'bill_depth_mm', 'flipper_length_mm', 'body_mass_g']]

Outputs you create

answer
  1. The requested result, with the values, labels and row order described by this task.
penguins · first 8 rows
islandbill_length_mmbill_depth_mmflipper_length_mmbody_mass_gsexyear
Torgersen39.118.71813750male2007
Torgersen39.517.41863800female2007
Torgersen40.3181953250female2007
Torgersen36.719.31933450female2007
Torgersen39.320.61903650male2007
Torgersen38.917.81813625female2007
Torgersen39.219.61954675male2007
Torgersen41.117.61823200female2007
Your task
  1. Sample 100 Penguin measurement rows with seed 42.
  2. Store the original values and indices in answer.
answer
Hints

Think: Original indices preserve the link between sampled observations and their measurements.

Tools: DataFrame.sample with random_state.

Approach: Take the requested reproducible sample without resetting its index.

Explained solution
answer=X.sample(100,random_state=42)

Retaining row identity lets later assignments and original-unit profiles remain aligned to the sampled population.

Ctrl/⌘+Enter: Run · Tab: indent · Esc then Tab: leave editor

Python loads when you run. Code and results stay in this activity only.

Run your code to inspect its output. Check uses that same run.