Sub topic 1
The ndarray: shape, ndim and dtype
Prerequisites
Assume you know basic Python lists, loops, functions, imports, and the basic idea of vectors and matrices.
The ndarray: shape, ndim and dtype
A NumPy ndarray is a multidimensional array whose elements usually share one data type.
shapeis a tuple giving the size of each dimension.ndimis the number of dimensions.dtypeis the type used to store each element, such asint64orfloat64.
For example, an array with shape (3, 4) has three rows and four columns.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a)
print(a.shape) # (3, 4)
print(a.ndim) # 2
print(a.dtype) # int64, or another integer dtype
print(a[1, 2]) # 6Creating arrays
np.array converts a sequence into an array. Functions such as np.zeros, np.ones, and np.arange create common patterns. reshape changes the shape without changing the element order. The new shape must contain the same number of elements.
zeros = np.zeros((2, 3))
values = np.arange(6).reshape(2, 3)Indexing and slicing
Use one index per dimension. A slice such as 1:3 selects a range and excludes its ending position.
print(values[0, 1]) # 1
print(values[:, 1]) # [1 4], every row in column 1
print(values[0, :2]) # [0 1], first two columnsViews versus copies
A basic slice usually creates a view, which is another way to access the same memory. Changing the view can change the original array. Use .copy() when you need independent data.
column = values[:, 1]
column[0] = 99
print(values[0, 1]) # 99
safe = values[:, 1].copy()
safe[0] = -1
print(values[0, 1]) # still 99Boolean masks and integer-array indexing
A Boolean mask selects elements where its entries are True. Integer-array indexing selects positions listed in another array. These forms generally create copies rather than views.
a = np.arange(6)
print(a[a % 2 == 0]) # [0 2 4]
print(a[[4, 1, 1]]) # [4 1 1]Exercise
What does a[:, 1] select from an array with shape (3, 4)?
Show answer
It selects every row from column 1, producing an array with shape (3,).