TExcelTAD
Home › Data Science › DS Exercises

DS Exercises

Time to practise! Each exercise has a starter playground that runs as-is and prints a placeholder result, so you can see the expected format. Replace the TODO parts, press ▶ Run, and compare your output with the "Expected" lines. Try for a few minutes before opening the solution.

Most exercises use a small slice of Riverside Bikes data — 12 days — so you can check results by eye:

Exercise Topic Lessons
1 Summary statistics Functions, Statistics Intro
2 Cleaning a messy column Data Preparation
3 Percentiles and the IQR rule Percentiles, Outliers
4 Group comparison Grouping & Aggregation
5 Correlation ranking Correlation, Correlation Matrix
6 Simple regression by hand Slope & Intercept, Linear Regression
7 Multiple regression with statsmodels Regression Coefficients, P-Value, R-Squared
8 Train/test evaluation Train/Test Split & Evaluation

1. Summary statistics

Print the mean, median, sample standard deviation and range of rides, each rounded to 1 decimal.

Expected:

text
mean=360.2 median=386.5 std=110.0 range=338
python · try it yourself
import pandas as pd

rides = pd.Series([414, 298, 439, 405, 254, 523, 497, 428, 209, 368, 302, 185])

mean = 0      # TODO
median = 0    # TODO
std = 0       # TODO (sample standard deviation)
rng = 0       # TODO (max - min)
print(f"mean={mean} median={median} std={std} range={rng}")
mean=0 median=0 std=0 range=0
Show solution
python
import pandas as pd

rides = pd.Series([414, 298, 439, 405, 254, 523, 497, 428, 209, 368, 302, 185])

mean = round(rides.mean(), 1)
median = rides.median()
std = round(rides.std(), 1)          # pandas uses ddof=1 by default
rng = rides.max() - rides.min()
print(f"mean={mean} median={median} std={std} range={rng}")

2. Cleaning a messy column

The station export has temperatures as text, with "n/a", a -999 sensor code and a comma as decimal separator in one row. Convert the column to numbers, treat -999 as missing, fill missing values with the median of the valid ones, and print the cleaned list and its mean (2 decimals).

Expected:

text
[24.1, 15.4, 22.1, 22.1, 6.4, 29.4, 22.1]
mean 20.23
python · try it yourself
import numpy as np
import pandas as pd

raw = pd.Series(["24.1", "15.4", "n/a", "22,1", "6.4", "29.4", "-999"])

clean = raw   # TODO: fix the comma, convert to numbers, -999 -> NaN, fill with median
print(clean.tolist())
print("mean", "TODO")
['24.1', '15.4', 'n/a', '22,1', '6.4', '29.4', '-999']
mean TODO
Show solution
python
import numpy as np
import pandas as pd

raw = pd.Series(["24.1", "15.4", "n/a", "22,1", "6.4", "29.4", "-999"])

clean = pd.to_numeric(raw.str.replace(",", "."), errors="coerce")
clean = clean.replace(-999, np.nan)
clean = clean.fillna(clean.median())
print(clean.tolist())
print("mean", round(clean.mean(), 2))

The valid values are 24.1, 15.4, 22.1, 6.4 and 29.4; their median is 22.1, which fills both gaps.

3. Percentiles and the IQR rule

Compute Q1, Q3 and the IQR of the trip lengths (in minutes) below, then list the trips outside the 1.5 × IQR fences.

Expected:

text
Q1=11.75 Q3=23.75 IQR=12.0
outliers: [95]
python · try it yourself
import pandas as pd

minutes = pd.Series([14, 32, 9, 21, 17, 95, 12, 26, 3, 18, 11, 23])

q1 = q3 = iqr = 0          # TODO
outliers = []              # TODO: values below q1 - 1.5*iqr or above q3 + 1.5*iqr
print(f"Q1={q1} Q3={q3} IQR={iqr}")
print("outliers:", outliers)
Q1=0 Q3=0 IQR=0
outliers: []
Show solution
python
import pandas as pd

minutes = pd.Series([14, 32, 9, 21, 17, 95, 12, 26, 3, 18, 11, 23])

q1, q3 = minutes.quantile([0.25, 0.75])
iqr = q3 - q1
low, high = q1 - 1.5 * iqr, q3 + 1.5 * iqr
outliers = minutes[(minutes < low) | (minutes > high)].tolist()
print(f"Q1={q1} Q3={q3} IQR={iqr}")
print("outliers:", outliers)

4. Group comparison

For each day_type, print the number of days and the mean rides (1 decimal), then the difference weekend − weekday.

Expected:

text
          days  mean_rides
day_type
weekday      9       346.3
weekend      3       428.3
difference: 82.0
python · try it yourself
import pandas as pd

days = pd.DataFrame({
    "day_type": ["weekday"] * 5 + ["weekend"] * 2 + ["weekday"] * 4 + ["weekend"],
    "rides": [414, 298, 439, 405, 254, 523, 497, 428, 209, 368, 302, 265],
})

summary = days.head(0)   # TODO: groupby + named aggregation (days, mean_rides)
print(summary)
print("difference:", "TODO")
Empty DataFrame
Columns: [day_type, rides]
Index: []
difference: TODO
Show solution
python
import pandas as pd

days = pd.DataFrame({
    "day_type": ["weekday"] * 5 + ["weekend"] * 2 + ["weekday"] * 4 + ["weekend"],
    "rides": [414, 298, 439, 405, 254, 523, 497, 428, 209, 368, 302, 265],
})

summary = days.groupby("day_type").agg(days=("rides", "size"),
                                       mean_rides=("rides", "mean")).round(1)
print(summary)
diff = summary.loc["weekend", "mean_rides"] - summary.loc["weekday", "mean_rides"]
print("difference:", round(diff, 1))

5. Correlation ranking

Rank the three predictors by the absolute value of their correlation with rides (strongest first) and print them with 2 decimals.

Expected:

text
temp_c      0.96
rain_mm    -0.69
humidity    0.14
python · try it yourself
import pandas as pd

df = pd.DataFrame({
    "temp_c":   [24.1, 15.4, 26.3, 22.1, 6.4, 29.4, 23.8, 24.4, 7.3, 15.7, 12.0, 5.2],
    "rain_mm":  [0, 0, 0, 0, 0, 0, 0, 0, 2.4, 0, 3.1, 6.0],
    "humidity": [85, 88, 48, 88, 41, 66, 63, 53, 36, 81, 70, 77],
    "rides":    [414, 298, 439, 405, 254, 523, 497, 428, 209, 368, 302, 185],
})

ranking = df.corr()["rides"]   # TODO: drop rides, sort by absolute value
print(ranking.round(2).to_string())
temp_c      0.96
rain_mm    -0.69
humidity    0.14
rides       1.00
Show solution
python
target = df.corr()["rides"].drop("rides")
ranking = target.reindex(target.abs().sort_values(ascending=False).index)
print(ranking.round(2).to_string())

6. Simple regression by hand

Using the same 12 days, compute the least-squares slope and intercept of rides on temp_c with the formulas slope = cov(x, y) / var(x) and intercept = mean(y) − slope × mean(x), then check against np.polyfit.

Expected:

text
slope=12.49 intercept=139.34
polyfit: 12.49 139.34
python · try it yourself
import numpy as np

temp = np.array([24.1, 15.4, 26.3, 22.1, 6.4, 29.4, 23.8, 24.4, 7.3, 15.7, 12.0, 5.2])
rides = np.array([414, 298, 439, 405, 254, 523, 497, 428, 209, 368, 302, 185])

slope = 0        # TODO: np.cov(temp, rides)[0, 1] / np.var(temp, ddof=1)
intercept = 0    # TODO
print(f"slope={slope:.2f} intercept={intercept:.2f}")
print("polyfit:", "TODO")
slope=0.00 intercept=0.00
polyfit: TODO
Show solution
python
slope = np.cov(temp, rides)[0, 1] / np.var(temp, ddof=1)
intercept = rides.mean() - slope * temp.mean()
print(f"slope={slope:.2f} intercept={intercept:.2f}")
s, i = np.polyfit(temp, rides, 1)
print("polyfit:", round(s, 2), round(i, 2))

np.cov uses ddof=1, so the variance must use ddof=1 as well — the factors then cancel.

7. Multiple regression with statsmodels

Fit rides ~ temp_c + rain_mm + humidity + weekend on the full 60-day dataset. Print the coefficients and p-values (3 decimals), the adjusted R², and the list of terms that are not significant at the 5 % level.

Expected (last two lines):

text
adj R2: 0.910
not significant: ['humidity']
python · try it yourself
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

# TODO: fit the model and print the results
print("adj R2:", "TODO")
print("not significant:", [])
adj R2: TODO
not significant: []
Show solution
python
model = smf.ols("rides ~ temp_c + rain_mm + humidity + weekend", data=bikes).fit()
print(pd.DataFrame({"coef": model.params, "p": model.pvalues}).round(3))
print(f"adj R2: {model.rsquared_adj:.3f}")
print("not significant:", list(model.pvalues[model.pvalues >= 0.05].index))

8. Train/test evaluation

Train rides ~ temp_c + rain_mm + weekend on the first 40 days and evaluate on the last 20. Print the MAE of the model and of the "training mean" baseline (1 decimal each).

Expected:

text
model MAE: 25.6
baseline MAE: 89.0
python · try it yourself
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

train, test = bikes, bikes     # TODO: first 40 / last 20 rows
print("model MAE:", "TODO")
print("baseline MAE:", "TODO")
model MAE: TODO
baseline MAE: TODO
Show solution
python
train, test = bikes.iloc[:40], bikes.iloc[40:]
model = smf.ols("rides ~ temp_c + rain_mm + weekend", data=train).fit()
model_mae = (test["rides"] - model.predict(test)).abs().mean()
baseline_mae = (test["rides"] - train["rides"].mean()).abs().mean()
print("model MAE:", round(model_mae, 1))
print("baseline MAE:", round(baseline_mae, 1))

Test yourself

In exercise 6, why must np.var use ddof=1 when combined with np.cov?

  1. np.var fails otherwise
  2. np.cov divides by n − 1, so both must use the same divisor for the factors to cancel
  3. It makes the slope positive
  4. It doesn't matter

In exercise 8, what does it mean if the model's MAE is far lower than the baseline's?

  1. The model overfits
  2. The model adds real predictive value over always predicting the mean
  3. The test set is too small
  4. The baseline is wrong