Skip to content

MLDay 2 of 50Foundations

Set Up Python, NumPy, pandas and matplotlib

You copy a line from a tutorial, it runs without an error, and your data doesn't change.

6 min read

You copy a line from a tutorial, it runs without an error, and your data doesn't change. The tutorial was written for pandas 2, and your laptop has pandas 3. One pinned setup means every line in this course does on your machine what it did on ours.

The idea

Four tools carry the whole course:

Tool What it holds You use it to
Python the language run every script
NumPy an array: a grid of numbers of one type do maths on every number at once
pandas a DataFrame: a table with named columns load, filter and summarize data
matplotlib a figure with one or more axes (plots) draw and save charts

A virtual environment (venv) is a private folder of packages for one project. You install exact pinned versions into it, so another project's upgrade can't break this one.

In code

1. Make the environment. Run this once in a terminal, in your course folder:

python3.12 -m venv .venv                # Windows: py -3.12 -m venv .venv
source .venv/bin/activate          # Windows: .venv\Scripts\activate
pip install numpy==2.5.5 pandas==3.1.1 matplotlib==3.11.2 scikit-learn==1.9.1

scikit-learn (the model-fitting library) arrives early, because Day 4 needs it. Later phases add their own packages on the day they're needed. Check that the install worked:

# script_id: day_002_setup_python_toolkit/check_setup
import sys

import matplotlib
import numpy as np
import pandas as pd

print("Python    ", sys.version.split()[0])
print("NumPy     ", np.__version__)
print("pandas    ", pd.__version__)
print("matplotlib", matplotlib.__version__)
Python     3.12.4
NumPy      2.5.5
pandas     3.1.1
matplotlib 3.11.2

2. NumPy: maths on a whole array. The bike-share file stores temperature as °C ÷ 41. One multiplication converts every value, with no loop. reshape(-1, 1) turns the flat list into a one-column table; the -1 means "work out the row count for me".

# script_id: day_002_setup_python_toolkit/numpy_arrays
import numpy as np

temp = np.array([0.24, 0.22, 0.22, 0.24, 0.24])  # the first five hours, °C ÷ 41
temp_c = temp * 41                                # every element at once
print(temp_c)
print("mean:", round(float(temp_c.mean()), 2), "°C")
print(temp_c.shape, "->", temp_c.reshape(-1, 1).shape)
[9.84 9.02 9.02 9.84 9.84]
mean: 9.51 °C
(5,) -> (5, 1)

The shape (5,) is a flat row of 5 numbers; (5, 1) is 5 rows and 1 column. scikit-learn wants the second.

3. pandas: load the table. These are 17,379 real hours of Capital Bikeshare rentals in Washington, D.C. The file is in the course's datasets/bike_sharing/ folder; run from the folder that holds datasets/, or set ML_DATA to its path. cnt is the number of rentals in that hour, and hr is the hour of the day, 0 to 23.

# script_id: day_002_setup_python_toolkit/bike_table
import os
from pathlib import Path

import pandas as pd

DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
df = pd.read_csv(DATA_DIR / "bike_sharing" / "hour.csv", parse_dates=["dteday"])  # dteday as real dates, not text
print(df.shape)                                   # (rows, columns)
print(df[["dteday", "hr", "temp", "cnt"]].head(3))
(17379, 17)
      dteday  hr  temp  cnt
0 2011-01-01   0  0.24   16
1 2011-01-01   1  0.22   40
2 2011-01-01   2  0.22   32

4. .loc: pick rows and columns by label. Inside the brackets, the rows come first, then the columns. Here the rows are a test, df["hr"] == 17, which keeps only the 5 pm hours.

# script_id: day_002_setup_python_toolkit/bike_table
rush = df.loc[df["hr"] == 17, ["dteday", "temp", "cnt"]]
print(len(rush), "hours at 5 pm")
print(rush.head(3))
730 hours at 5 pm
       dteday  temp  cnt
17 2011-01-01  0.44   67
40 2011-01-02  0.34   65
62 2011-01-03  0.24  157

5. Change data the pandas 3 way. Two habits cover it. To make a new version of the table, reassign the result. To change cells, use one .loc call. Only 3 hours have weather code 4 (heavy rain or snow), so this folds them into code 3 (light rain):

# script_id: day_002_setup_python_toolkit/bike_table
df = df.assign(temp_c=df["temp"] * 41)            # a new column: reassign the result
df.loc[df["weathersit"] == 4, "weathersit"] = 3   # change cells: one .loc call
print(df["weathersit"].value_counts().sort_index().to_dict())
{1: 11413, 2: 4544, 3: 1422}
Old habit In pandas 3 Do this instead
df["cnt"][0] = 17 (chained assignment: two brackets in a row) changes nothing, and warns ChainedAssignmentError df.loc[0, "cnt"] = 17
df.dropna(inplace=True) returns None, and warns Pandas4Warning (deprecated since pandas 3.1) df = df.dropna()

6. groupby: one summary per group. It splits the rows by a column's values, then summarizes each group. Here: the mean rentals for each hour of the day.

# script_id: day_002_setup_python_toolkit/bike_table
by_hour = df.groupby("hr")["cnt"].mean()          # 24 groups, one mean each
print(by_hour.round(1).loc[[3, 8, 17]])
hr
3      11.7
8     359.0
17    461.5
Name: cnt, dtype: float64

7. matplotlib: save one chart. plt.subplots returns a figure (the image) and an axes (the plot on it). You draw on ax and save fig.

# script_id: day_002_setup_python_toolkit/bike_table
import matplotlib.pyplot as plt

FIG_DIR = Path(os.environ.get("ML_FIG_DIR", "figures"))
FIG_DIR.mkdir(exist_ok=True)

fig, ax = plt.subplots(figsize=(6, 4))
ax.bar(by_hour.index, by_hour.values, color="#2a78d6")
ax.set(title="Rentals peak at 8 am and 5 pm", xlabel="Hour of day", ylabel="Mean rentals per hour")
fig.tight_layout()
fig.savefig(FIG_DIR / "rentals_by_hour.png", dpi=120)
plt.close(fig)
print("saved rentals_by_hour.png")
saved rentals_by_hour.png

Rentals peak at 8 am and 5 pm

Commuters make two peaks: about 359 rentals an hour at 8 am and 461 at 5 pm. At 4 am the mean is 6.

Quick check

Quick check

1. What shape does np.array([1, 2, 3]).reshape(-1, 1) have?

2. In pandas 3, what does df["cnt"][0] = 17 do?

3. What does df.groupby("hr")["cnt"].mean() return for the bike-share table?

Next

The table is loaded; now look at it properly. Day 3: Explore Data Before Modelling plots its distributions and relationships before any model is trained.

Data: Bike Sharing Dataset (UCI Machine Learning Repository, dataset 275), CC BY 4.0; cite Fanaee-T, H. and Gama, J. (2013), "Event labeling combining ensemble detectors and background knowledge", Progress in Artificial Intelligence, doi:10.1007/s13748-013-0040-3.

Next · Day 3 · 7 minExplore Data Before Modelling← Previous: Day 1 · When to Use Machine Learning (and When Not To)
Not tapped yet