MathubLearn / Practice / Excel
CSCI 127 Joy and Beauty of Data · Unit 4: Data science · on Final exam (Exam 3)

4.1 NumPy arrays

Study notes for NumPy arrays in CSCI 127 Joy and Beauty of Data at Montana State University: the big ideas, code you should know, a worked example, common mistakes and an exam tip. The same topic has endless practice questions and flashcards in Mathub.

Big ideas

Code you should know

Element-wise math and reductions
import numpy as np

temps = np.array([61, 68, 75, 80, 72])
print(temps * 2)
print((temps - 32) * 5 / 9)
print(temps.mean(), temps.max(), temps.argmax())
print(temps[temps > 70], (temps > 70).sum())
print(np.arange(0, 10, 3), np.linspace(0, 1, 5))
Output
[122 136 150 160 144]
[16.11 20.   23.89 26.67 22.22]
71.2 80 3
[75 80 72] 3
[0 3 6 9] [0.   0.25 0.5  0.75 1.  ]
2-D arrays and axes
import numpy as np

grid = np.array([[1, 2, 3], [4, 5, 6]])
print(grid.shape, grid.size, grid[1, 2], grid[:, 0])
print(grid.sum(axis=0), grid.sum(axis=1))
print(np.zeros((2, 2)), np.ones(3))
Output
(2, 3) 6 6 [1 4]
[5 7 9] [ 6 15]
[[0. 0.]
 [0. 0.]] [1. 1. 1.]

Worked example

With a = np.array([2, 4, 6, 8]), what are a[1:3] * 10, (a > 4).sum() and a.mean()?
Show the solution
[40 60], 2 (6 and 8), and 5.0.

Common mistakes

Exam tipKnow arange versus linspace, boolean masks, and the axis rule (0 = down the rows, 1 = across the columns).

Keep going in Mathub

Mathub is free for Montana State students: an endless quizzer with worked explanations, one-question lessons, flashcards, exam prep checklists, the class calendar with every deadline, a grade calculator and a study board for CSCI 127.