Puzzled on the ndim from Numpy

Question:

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

Asked By: ColinBinWang

||

Answers:

zerogives an array of zeros with dimensions you specify:

>>> b = np.zeros((2,3,4), dtype=np.int16)  
>>> b 
array([[[0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0]],

       [[0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0]]], dtype=int16)

For b you give three dimensions but for a you give four. Count the opening [.

>>> a = np.zeros((5,2,3,4), dtype=np.int16)
>>> a 
array([[[[0, 0, 0, 0],
         [0, 0, 0, 0],
         [0, 0, 0, 0]],

        [[0, 0, 0, 0],
         [0, 0, 0, 0],
         [0, 0, 0, 0]]],


...

shape echos back the dimensions you specified:

>>> a.shape
(5, 2, 3, 4)

>>> b.shape
(2, 3, 4)
Answered By: Mike Müller

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.

Answered By: lvc
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.