NumPy & pandas for ML
Every scikit-learn model consumes the same thing: a 2-D table of numbers X (rows = samples, columns = features) and, for supervised learning, a 1-D array y. Getting your data into that shape is a large part of real ML work. This lesson collects the NumPy and pandas skills you need most often.
Shapes: the first thing to check
import numpy as np
y = np.array([3.1, 2.4, 5.0, 4.2])
print("y shape:", y.shape, " ndim:", y.ndim)
X_one_feature = y.reshape(-1, 1) # -1 means "work out this size for me"
print("as one column:", X_one_feature.shape)
X = np.array([[1.0, 20, 0],
[2.0, 35, 1],
[1.5, 28, 1],
[3.0, 41, 0]])
print("X shape:", X.shape, "-> samples:", X.shape[0], " features:", X.shape[1])
print("second column (all rows):", X[:, 1])
print("last two rows:\n", X[2:])y shape: (4,) ndim: 1
as one column: (4, 1)
X shape: (4, 3) -> samples: 4 features: 3
second column (all rows): [20. 35. 28. 41.]
last two rows:
[[ 1.5 28. 1. ]
[ 3. 41. 0. ]]
The most common beginner error in scikit-learn is passing a 1-D array as X. The message ("Expected 2D array, got 1D array instead") even suggests the fix: reshape(-1, 1) for a single feature.
Vectorised maths
NumPy applies operations to whole arrays at once — no loops needed. This is both shorter and much faster:
import numpy as np
prices = np.array([12.5, 8.0, 15.25, 9.9])
qty = np.array([2, 5, 1, 3])
print("line totals:", prices * qty)
print("order total:", (prices * qty).sum())
print("with 20% tax:", (prices * 1.2).round(2))
print("log of prices:", np.log(prices).round(3))
X = np.array([[1, 200], [2, 300], [3, 400]], dtype=float)
print("column means:", X.mean(axis=0)) # axis=0 -> down the rows
print("row sums: ", X.sum(axis=1)) # axis=1 -> across the columnsline totals: [25. 40. 15.25 29.7 ]
order total: 109.95
with 20% tax: [15. 9.6 18.3 11.88]
log of prices: [2.526 2.079 2.725 2.293]
column means: [ 2. 300.]
row sums: [201. 302. 403.]
axis=0 collapses the rows (one result per column); axis=1 collapses the columns (one result per row). Feature-wise statistics almost always use axis=0.
Boolean masks: filtering rows
A comparison produces an array of True/False, which can select rows. This is how you filter data, count classes and pick out mistakes:
import numpy as np
y_true = np.array([1, 0, 1, 1, 0, 0, 1, 0])
y_pred = np.array([1, 0, 0, 1, 0, 1, 1, 0])
scores = np.array([0.9, 0.2, 0.4, 0.8, 0.1, 0.6, 0.7, 0.3])
correct = y_true == y_pred
print("correct mask:", correct)
print("accuracy:", correct.mean())
print("wrong rows:", np.where(~correct)[0])
print("scores of the positives:", scores[y_true == 1])
print("class counts:", np.bincount(y_true))correct mask: [ True True False True True False True True]
accuracy: 0.75
wrong rows: [2 5]
scores of the positives: [0.9 0.4 0.8 0.7]
class counts: [4 4]
From pandas to X and y
Data usually arrives as a DataFrame. Pick the target column for y and the feature columns for X. scikit-learn accepts DataFrames directly and remembers the column names:
import io
import pandas as pd
from sklearn.linear_model import LinearRegression
csv = """sqm,rooms,floor,balcony,rent
45,2,1,no,690
62,3,4,yes,880
38,1,2,no,560
75,3,3,yes,1020
55,2,0,no,760
90,4,5,yes,1260"""
df = pd.read_csv(io.StringIO(csv))
df["balcony"] = (df["balcony"] == "yes").astype(int) # text -> 0/1
X = df.drop(columns="rent")
y = df["rent"]
print("feature columns:", list(X.columns))
print("X:", X.shape, " y:", y.shape)
model = LinearRegression().fit(X, y)
print("model saw features:", list(model.feature_names_in_))
print("values for NumPy-only tools:", type(X.to_numpy()).__name__, X.to_numpy().shape)feature columns: ['sqm', 'rooms', 'floor', 'balcony']
X: (6, 4) y: (6,)
model saw features: ['sqm', 'rooms', 'floor', 'balcony']
values for NumPy-only tools: ndarray (6, 4)
Quick exploration helpers
A handful of pandas calls answer most "what does my data look like?" questions:
import pandas as pd
from sklearn.datasets import load_wine
wine = load_wine(as_frame=True).frame
print(wine.shape)
print(wine["target"].value_counts().sort_index())
print()
print(wine[["alcohol", "malic_acid", "color_intensity"]].describe().round(2))
print()
print("mean alcohol per cultivar:")
print(wine.groupby("target")["alcohol"].mean().round(2))(178, 14)
target
0 59
1 71
2 48
Name: count, dtype: int64
alcohol malic_acid color_intensity
count 178.00 178.00 178.00
mean 13.00 2.34 5.06
std 0.81 1.12 2.32
min 11.03 0.74 1.28
25% 12.36 1.60 3.22
50% 13.05 1.87 4.69
75% 13.68 3.08 6.20
max 14.83 5.80 13.00
mean alcohol per cultivar:
target
0 13.74
1 12.28
2 13.15
Name: alcohol, dtype: float64
| Call | Tells you |
|---|---|
df.shape, df.dtypes |
size and column types |
df.head(), df.sample(5, random_state=0) |
a peek at the rows |
df.describe() |
count, mean, std, quartiles per column |
df.isna().sum() |
missing values per column |
df["col"].value_counts() |
class balance / category frequencies |
df.groupby("label").mean() |
how features differ between classes |
df.corr() |
pairwise linear correlations |
Tip:
load_*(as_frame=True)returns the built-in scikit-learn data sets as pandas tables with proper column names, which is much nicer for exploring than raw arrays.
Test yourself
What shape does scikit-learn expect for X?
- (n_features,)
- (n_samples, n_features)
- (n_features, n_samples)
- Any shape
For X with shape (100, 4), what is the shape of X.mean(axis=0)?
- (100,)
- (4,)
- (1,)
- (100, 4)
What does (y_true == y_pred).mean() compute?
- The number of errors
- The accuracy
- The mean of the labels
- Nothing useful