How do I get the dimensions of an array? For instance, this is 2×2:
a = np.array([[1,2],[3,4]])
.shape to obtain a tuple of array dimensions:
>>> a.shape (2, 2)
import numpy as np >>> np.shape(a) (2,2)
Also works if the input is not a numpy array but a list of lists
>>> a = [[1,2],[1,2]] >>> np.shape(a) (2,2)
Or a tuple of tuples
>>> a = ((1,2),(1,2)) >>> np.shape(a) (2,2)
By convention, in Python world, the shortcut for
In : import numpy as np In : a = np.array([[1,2],[3,4]])
In Numpy, dimension, axis/axes, shape are related and sometimes similar concepts:
In Mathematics/Physics, dimension or dimensionality is informally defined as the minimum number of coordinates needed to specify any point within a space. But in Numpy, according to the numpy doc, it’s the same as axis/axes:
In Numpy dimensions are called axes. The number of axes is rank.
In : a.ndim # num of dimensions/axes, *Mathematics definition of dimension* Out: 2
the nth coordinate to index an
array in Numpy. And multidimensional arrays can have one index per axis.
In : a[1,0] # to index `a`, we specific 1 at the first axis and 0 at the second axis. Out: 3 # which results in 3 (locate at the row 1 and column 0, 0-based index)
describes how many data (or the range) along each available axis.
In : a.shape Out: (2, 2) # both the first and second axis have 2 (columns/rows/pages/blocks/...) data
shape method requires that
a be a Numpy ndarray. But Numpy can also calculate the shape of iterables of pure python objects:
In: a = np.array([[1,2,3],[4,5,6]]) In: a.shape Out: (2, 3) In: a.shape # x axis Out: 2 In: a.shape # y axis Out: 3
You can use
.ndim for dimension and
.shape to know the exact dimension:
>>> var = np.array([[1,2,3,4,5,6], [1,2,3,4,5,6]]) >>> var.ndim 2 >>> varshape (2, 6)
You can change the dimension using
>>> var_ = var.reshape(3, 4) >>> var_.ndim 2 >>> var_.shape (3, 4)
a.shape is just a limited version of
np.info(). Check this out:
import numpy as np a = np.array([[1,2],[1,2]]) np.info(a)
class: ndarray shape: (2, 2) strides: (8, 4) itemsize: 4 aligned: True contiguous: True fortran: False data pointer: 0x27509cf0560 byteorder: little byteswap: False type: int32
rows = a.shape # 2 cols = a.shape # 2 a.shape #(2,2) a.size # rows * cols = 4
Execute below code block in python notebook.
import numpy as np a = np.array([[1,2],[1,2]]) print(a.shape) print(type(a.shape)) print(a.shape)
then you realized that
a.shape is a tuple.
so you can get any dimension’s size by
a.shape[index of dimention]