Shape of NumPy Arrays
Start your free 7-days trial now!
Introduction
The shape
property of a NumPy array is a tuple that tells us the size of the each nested array. This property is most commonly used to access the number of rows and columns of a 2D NumPy array.
Example
Get number of rows and columns of a 2D array
We want to get the number of rows and columns of a 2D NumPy array. The code is straight-forward:
Here, our NumPy array x
has 2 rows and 3 columns.
Extracting the values from the shape property
Since shape
is a tuple, we can access the values using array-like notation:
Misconceptions
Shape of a 1D array
The shape of a 1D array can be a source of confusion for those who think of NumPy arrays as vectors/matrices.
Example
Suppose we have the following code snippet:
Somewhat confusingly, the presence of the comma may deceive you into thinking our x
is two-dimensional. However, we know that x
is one-dimensional as it's simply [1,2,3]
. Therefore, if you see ,
followed by nothing, you have yourself a flattened array, or a vector for the mathematically-inclined. In addition, the (3,)
just means that you have 3 elements in your array, and it has nothing to do with the number of rows and columns.
Rows/Column interpretation only work for 2D arrays. The catch is that the shape
property can be interpreted as the number of rows and columns for 2D arrays only. If we think of np.array([1,2,3])
as a vector, or a 3 by 1 matrix, we may be inclined to think of its shape as (3,1)
. While thinking in terms of vectors and matrices is helpful in the world of NumPy, we still need to keep in mind the subtlety of the shape property. The shape property gives us the size of the array in each of its dimension, which does not necessarily equate to the number of rows and columns. For 2D arrays though, the shape does correspond to rows and columns.