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
import numpy as np. An array holds many numbers of one type and does math on all of them at once:a * 2,a + b,a ** 2(element-wise, no loop).- Making arrays:
np.array([1, 2, 3]),np.arange(0, 10, 2),np.linspace(0, 1, 5),np.zeros(4),np.ones((2, 3)),np.random.randint(1, 7, size=10). a.shape,a.size,a.dtype. Index and slice like lists; 2-D arrays usea[row, col],a[:, 0]for a column.- Boolean masks filter:
a[a > 5];(a > 5).sum()counts. Reductions:a.sum(), a.mean(), a.max(), a.argmax(), a.std(), withaxis=0down columns oraxis=1across rows. - Arrays are the fast, memory-light way to hold data; pandas and matplotlib are built on them.
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
- Mixing a Python list and an array:
[1, 2] * 2repeats the list;np.array([1, 2]) * 2doubles the numbers. - Off-by-one with
arange(stop excluded) versuslinspace(stop included). - Forgetting
axisand getting a single number when you wanted per-column results.
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.