# Python numpy ndarray.shape and ndarray.ndim problem

created at 07-30-2021 views: 8

## ndarray.dim¶

According to my understanding, the definition of dimension in numpy refers specifically to the number of nesting levels, rather than calculating according to the definition of dimension in the matrix. I was very confused at the beginning, but I understood it later.

example

c=np.array(
[1, 2, 3, 4]
)
print('Dimension:'+str(c.ndim))

PS C:\Users\Yooooooooooooooooomu\Desktop\torment-master> python test02.py
Dimension:1


c=np.array(
[[1, 2, 3, 4]]
)
print('Dimension:'+str(c.ndim))

PS C:\Users\Yooooooooooooooooomu\Desktop\torment-master> python test02.py
Dimension:2


And so on.

## ndarray.shape¶

According to my understanding, shape returns the number of elements in each layer, from the outside to the inside.

example

    c=np.array(
[
[
[[1],[1]],
[[1],[1]],
[[1],[1]]
],
[
[[1],[1]],
[[1],[1]],
[[1],[1]]
],
[
[[1],[1]],
[[1],[1]],
[[1],[1]]
],
[
[[1],[1]],
[[1],[1]],
[[1],[1]]
]
]
)
print('shape:'+str(c.shape))


As you can see, this is a four-level nested ndarray. The outermost layer contains four third-level arrays. Each third-level array contains three second-level arrays, each of which is a second-level array. It also contains two one-level arrays, one-level array contains one element, and the return value of shape is (4,3,2,1).

PS C:\Users\Yooooooooooooooooomu\Desktop\torment-master> python test02.py
shape:(4, 3, 2, 1)


I checked a lot of articles on this question but did not find a detailed answer. I hope this article can help more people who encounter the same problem.

created at:07-30-2021