yourarray.shape
or np.shape()
or np.ma.shape()
returns the shape of your ndarray as a tuple; And you can get the (number of) dimensions of your array using yourarray.ndim
or np.ndim()
. (i.e. it gives the n
of the ndarray
since all arrays in NumPy are just n-dimensional arrays (shortly called as ndarray
s))
For a 1D array, the shape would be (n,)
where n
is the number of elements in your array.
For a 2D array, the shape would be (n,m)
where n
is the number of rows and m
is the number of columns in your array.
Please note that in 1D case, the shape would simply be (n, )
instead of what you said as either (1, n)
or (n, 1)
for row and column vectors respectively.
This is to follow the convention that:
For 1D array, return a shape tuple with only 1 element (i.e. (n,)
)
For 2D array, return a shape tuple with only 2 elements (i.e. (n,m)
)
For 3D array, return a shape tuple with only 3 elements (i.e. (n,m,k)
)
For 4D array, return a shape tuple with only 4 elements (i.e. (n,m,k,j)
)
and so on.
Also, please see the example below to see how np.shape()
or np.ma.shape()
behaves with 1D arrays and scalars:
# sample array
In [10]: u = np.arange(10)
# get its shape
In [11]: np.shape(u) # u.shape
Out[11]: (10,)
# get array dimension using `np.ndim`
In [12]: np.ndim(u)
Out[12]: 1
In [13]: np.shape(np.mean(u))
Out[13]: () # empty tuple (to indicate that a scalar is a 0D array).
# check using `numpy.ndim`
In [14]: np.ndim(np.mean(u))
Out[14]: 0
P.S.: So, the shape tuple is consistent with our understanding of dimensions of space, at least mathematically.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…