Consider:
import numpy as np>>> a=np.array([1, 2, 3, 4])>>> aarray([1, 2, 3, 4])>>> a.ndim1
How is the dimension 1? I have given a equation of three variables. It means it is three-dimensional, but it is showing the dimension as 1. What is the logic of ndim?
Best Answer
As the NumPy documentation says, numpy.ndim(a)
returns:
The number of dimensions in
a
. Scalars are zero-dimensional
E.g.:
a = np.array(111)b = np.array([1,2])c = np.array([[1,2], [4,5]])d = np.array([[1,2,3,], [4,5]])print a.ndim, b.ndim, c.ndim, d.ndim#outputs: 0 1 2 1
Note that the last array, d
, is an array of object dtype
, so its dimension is still 1
.
What you want to use could be a.shape
(or a.size
for a one-dimensional array):
print a.size, b.sizeprint c.size # == 4, which is the total number of elements in the array# Outputs:1 24
Method .shape
returns you a tuple
, and you should get your dimension using [0]
:
print a.shape, b.shape, b.shape[0]() (2L,) 2