11 Numpy Cheat Sheet
11 Numpy Cheat Sheet
Axis 0
Axis 0
Axis 1 Axis 1
→ a.ndim = 1 „axis 0“ → a.ndim = 2 „axis 0 and axis 1“ → a.ndim = 3 „axis 0 and axis 1“
→ a.shape = (5,) „five rows“ → a.shape = (5, 4) „five rows, four cols“ → a.shape = (5, 4, 3) „5 rows, 4 cols, 3 levels“
→ a.size = 5 „5 elements“ → a.size = 20 „5*4=20 elements“ → a.size = 60 „5*4*3=60 elements“
Goal: bring arrays with different shapes into the same shape Goal: find elements that meet a certain condition in a NumPy array
during arithmetic operations. NumPy does that for you! • Step 1: Understanding np.nonzero()
indices = np.array([[False, False, True], cities = np.array(["Hong Kong", "New York", "Berlin",
[False, False, False], "Montreal"])
[True, True, False]])
# Find cities with above average pollution
print(a[indices]) polluted = set(cities[np.nonzero(X > np.average(X))[0]])
# [3 7 8] print(polluted)
We create two arrays “a” and “indices”. The first array contains The Boolean expression “X > np.average(X)” uses broadcasting
two-dimensional numerical data (=data array). The second to bring both operands to the same shape. Then it performs an
array has the same shape and contains Boolean values element-wise comparison to determine a Boolean array that
(=indexing array). You can use the indexing array for fine- contains “True” if the respective measurement observed an
grained data array access. This creates a new NumPy array from above average AQI value. The function np.average() computes
the data array containing only those elements for which the the average AQI value over all NumPy array elements. Boolean
indexing array contains “True” Boolean values at the respective indexing accesses all city rows with above average pollution
array positions. Thus, the resulting array contains the three values.
values 3, 7, and 8.