import numpy as np a = np.zeros((5,2,3,4), dtype=np.int16) print a.ndim b = np.zeros((2,3,4), dtype=np.int16) print b.ndim
Above is my code. the output is:
4 3
I have checked the page from [here] (Link)
I expected a.dim = 2 or 3, but it is 4. Why?
Could you give me some hints? Thanks
Advertisement
Answer
The tuple you give to zeros
and other similar functions gives the ‘shape’ of the array (and is available for any array as a.shape
). The number of dimensions is the number of entries in that shape.
If you were instead printing len(a.shape)
and len(b.shape)
you would expect the result you get. The ndim
is always equal to this (because that’s how it’s defined).
The link you give shows the same behavior, except that the reshape
method takes arbitary numbers of positional arguments rather than a tuple. But in the tutorial’s example:
>>> a = arange(15).reshape(3, 5) >>> a array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]]) >>> a.shape (3, 5) >>> a.ndim 2
The number of arguments given to reshape
, and the number of elements in the tuple given back by a.shape
, is 2. If this was instead:
>>> a = np.arange(30).reshape(3, 5, 2) >>> a.ndim 3
Then we see the same behavior: the ndim
is the number of shape entries we gave to numpy.