NumPy Array Attributes
Every NumPy array comes with built-in attributes that describe its structure - its dimensions, size, and the type of data it holds - which are essential to check whenever you're debugging shape mismatches or preparing data for a model.
Key Array Attributes
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.shape) # (2, 3) - 2 rows, 3 columns
print(arr.ndim) # 2 - number of dimensions
print(arr.size) # 6 - total number of elements
print(arr.dtype) # int64 - the data type of the elements
Reshaping an Array
The reshape() method changes an array's shape without changing its data, as long as the total number of elements stays the same.
import numpy as np
arr = np.arange(12) # [0, 1, 2, ..., 11]
reshaped = arr.reshape(3, 4) # reshape into 3 rows, 4 columns
print(reshaped)
flattened = reshaped.flatten() # convert back to a 1D array
Changing Data Type
import numpy as np
arr = np.array([1, 2, 3])
float_arr = arr.astype(float)
print(float_arr) # [1. 2. 3.]
A huge number of NumPy errors in real projects come down to a shape mismatch between arrays - regularly checking .shape while debugging is one of the fastest ways to catch these issues.
Coming Up Next
To close out this section, the final topic covers Matrix Product - how NumPy performs matrix multiplication, a core operation behind many Machine Learning algorithms.