Skip to content

AIPrimer A02Before Day 2

NumPy and pandas Basics

Every model in this course eats a grid of numbers and returns another.

8 min read · outside the 100 days

Every model in this course eats a grid of numbers and returns another. This primer covers the moves the lessons make without stopping to explain: picking rows and columns, counting with True and False, and summarizing a whole column in one call.

Read before: Day 2 · about 20 minutes

Arrays: shape, type and indexing

A NumPy array is a grid of numbers that all share one dtype (data type), such as float64 or int64. Its shape gives its size: (4, 3) means 4 rows and 3 columns. Counting starts at 0, so row 2 is the third row.

In this course a row is one example (an hour, a message, an image) and a column is one feature. Models read an array the same way, so most shape errors come from a grid turned the wrong way round.

Inside the brackets, rows come first, then columns, split by a comma. A colon : alone means "all of them", and 1:3 means "from 1 up to, but not including, 3".

# script_id: primer_a02/arrays
import numpy as np

X = np.array([[12.0, 0.81, 3],    # one row per hour: temperature (°C), humidity, rentals
              [18.0, 0.55, 40],
              [25.0, 0.42, 96],
              [ 9.0, 0.93, 1]])
print(X.shape, X.dtype)          # 4 rows, 3 columns, all floats
print(X[2])                      # row 2 (counting from 0)
print(X[:, 0])                   # every row, column 0
print(X[1:3, 2])                 # rows 1 and 2, column 2
print(X[:, 2].astype(int))       # floats -> whole numbers
print(np.column_stack([X[:, 0], X[:, 1]]).shape)  # 1-D columns side by side
(4, 3) float64
[25.    0.42 96.  ]
[12. 18. 25.  9.]
[40. 96.]
[ 3 40 96  1]
(4, 2)

The rentals were typed as whole numbers, yet they print as 3., 40.: one array holds one type, so NumPy made them all floats. .astype(int) converts them back. np.column_stack glues 1-D columns side by side into a table.

Masks: True and False do the counting

A comparison such as y_pred == y_true checks every element at once and returns a mask: an array of True and False. Python counts True as 1 and False as 0. So .sum() counts the matches, and .mean() gives the share that match. Put a mask inside the brackets, and you keep only the elements where it is True.

Worked: the guesses [1, 0, 0, 1, 1, 0] against the truth [1, 0, 1, 1, 0, 0] match in 4 of 6 places, so the accuracy is 4 ÷ 6 ≈ 0.667.

# script_id: primer_a02/masks
import numpy as np

y_true = np.array([1, 0, 1, 1, 0, 0])   # 1 = spam
y_pred = np.array([1, 0, 0, 1, 1, 0])   # a model's guesses
right = y_pred == y_true                # True where the guess matches
print(right)
print("right:", right.sum(), "of", len(right))
print("accuracy:", round(float(right.mean()), 3))
missed = (y_true == 1) & (y_pred == 0)  # spam the model let through
print("missed spam:", missed.sum())
print("guesses on real spam:", y_pred[y_true == 1])
print(np.where(y_pred == 1, "spam", "ok"))
[ True  True False  True False  True]
right: 4 of 6
accuracy: 0.667
missed spam: 1
guesses on real spam: [1 0 1]
['spam' 'ok' 'ok' 'spam' 'spam' 'ok']

Join masks with & (and), | (or) and ~ (not). np.where(mask, a, b) takes a where the mask is True and b where it is False.

Axis: down the columns or across the rows

On a 2-D array, .mean() alone gives one number for the whole grid. The axis says which way to collapse it. axis=0 works down the rows, giving one result per column. axis=1 works across the columns, giving one result per row.

Subtracting a single row from the whole array subtracts it from every row. This is called broadcasting. X - X.mean(axis=0) uses it to center each column on 0, the first half of standardizing in Day 9.

# script_id: primer_a02/axis
import numpy as np

X = np.array([[12.0, 0.8],
              [18.0, 0.6],
              [24.0, 0.4]])
print("column means:", X.mean(axis=0))      # down each column
print("row sums:    ", X.sum(axis=1))       # across each row
centered = X - X.mean(axis=0)               # each row minus the mean row
print(centered.round(2))

probs = np.array([[0.7, 0.2, 0.1],          # one row per image, one column per class
                  [0.1, 0.3, 0.6]])
print("best class per row:", probs.argmax(axis=1))
column means: [18.   0.6]
row sums:     [12.8 18.6 24.4]
[[-6.   0.2]
 [ 0.   0. ]
 [ 6.  -0.2]]
best class per row: [0 2]

argmax returns the position of the largest value, not the value itself. Row 1's largest is 0.6, at position 2.

Random numbers you can repeat

Many lessons make up small data sets. np.random.default_rng(42) makes a random generator, and the 42 is its seed, a starting point. The same seed gives the same numbers on every run and every laptop with the course's pinned NumPy, so your output matches the lesson's. A new seed gives new numbers, but the same ones again on every rerun.

Four calls cover most uses: random for numbers between 0 and 1, uniform for numbers spread evenly between two limits, integers for whole numbers, and normal for bell-shaped noise around a mean. A mask such as rng.random(1000) < 0.15 is True about 15% of the time, which is how a lesson makes up labels with a set share of 1s.

# script_id: primer_a02/seeded_rng
import numpy as np

rng = np.random.default_rng(42)              # a seeded generator
print(rng.random(3).round(3))                # 3 numbers between 0 and 1
print(rng.integers(0, 10, size=5))           # 5 whole numbers from 0 to 9
print(rng.normal(20, 5, size=3).round(1))    # 3 draws, mean 20, spread 5
print(rng.uniform(50, 100, size=3).round(1))  # 3 numbers spread evenly from 50 to 100

again = np.random.default_rng(42)            # same seed ...
print(again.random(3).round(3))              # ... same numbers
[0.774 0.439 0.859]
[0 6 2 0 5]
[20.6 18.4 19.9]
[72.5 68.5 96.3]
[0.774 0.439 0.859]

pandas: Series, DataFrame and back to NumPy

A DataFrame is a table with named columns; each column alone is a Series. One name in the brackets, df["cnt"], gives a Series. A list of names, df[["cnt"]], gives a DataFrame, even with one column inside. scikit-learn wants a table for the features, so lessons write df[["temp_c"]].

.loc picks rows by label (Day 2 uses it on the real table); .iloc picks them by position, like a NumPy array. A mask filters rows the same way it filters an array, and .isin tests a column against a list of values. .to_numpy() turns a table into a plain array.

# script_id: primer_a02/pandas_basics
import pandas as pd

df = pd.DataFrame({"hr": [7, 8, 12, 17, 23],
                   "temp_c": [9.8, 11.5, 18.0, 21.3, 14.0],
                   "cnt": [180, 359, 250, 461, 90]})
print(type(df["cnt"]).__name__, df["cnt"].shape)        # one column: a Series
print(type(df[["cnt"]]).__name__, df[["cnt"]].shape)    # a list of columns: a DataFrame
print(df.iloc[[0, -1]])                                 # first and last rows, by position
busy = df[df["hr"].isin([8, 17]) & (df["cnt"] > 400)]   # rush hour and busy
print(busy)
print(df.sort_values("cnt", ascending=False)["hr"].to_numpy())
X = df[["hr", "temp_c"]].to_numpy()                     # to NumPy for a model
print(X.shape, X.dtype)
Series (5,)
DataFrame (5, 1)
   hr  temp_c  cnt
0   7     9.8  180
4  23    14.0   90
   hr  temp_c  cnt
3  17    21.3  461
[17  8 12  7 23]
(5, 2) float64

A Series has shape (5,), flat like a 1-D array; the one-column DataFrame is (5, 1). Position -1 counts from the end, so iloc[[0, -1]] gives the first and last rows. The busiest hour is 17 (5 pm), then 8 am.

Quick check

Quick check

1. X has shape (100, 3). What shape does X.mean(axis=0) have?

2. y_pred == y_true gives [True, False, True, True]. What does .mean() return?

3. What is the difference between df["cnt"] and df[["cnt"]]?

Next

With these moves in hand, Day 2: Set Up Python, NumPy, pandas and matplotlib loads the real bike-share table, and every later lesson builds on the same few calls.