70

I want to check if a numpy array is multidimensional or not?

V = [[ -7.94627203e+01  -1.81562235e+02  -3.05418070e+02  -2.38451033e+02][  9.43740653e+01   1.69312771e+02   1.68545575e+01  -1.44450299e+02][  5.61599000e+00   8.76135909e+01   1.18959245e+02  -1.44049237e+02]]

How can I do that in numpy?

3 Answers 3

126

Use the .ndim property of the ndarray:

>>> a = np.array([[ -7.94627203e+01,  -1.81562235e+02,  -3.05418070e+02,  -2.38451033e+02],[  9.43740653e+01,   1.69312771e+02,   1.68545575e+01,  -1.44450299e+02],[  5.61599000e+00,   8.76135909e+01,   1.18959245e+02,  -1.44049237e+02]])
>>> a.ndim
2
Sign up to request clarification or add additional context in comments.

Comments

9

In some cases, you should also add np.squeeze() to make sure there are no "empty" dimensions

>>> a = np.array([[1,2,3]])
>>> a.ndim
2
>>> a = np.squeeze(a)
>>> a .ndim
1

Comments

0

You can use .shape property too, which gives you a tuple containing the length of each dimension. Therefore, to get the dimension using .shape you could aswell call len() on the resulting tuple:

import numpy as np

a = np.array([1,2,3])
b = np.array([[1,2,3]])
c = np.array([[1,2,3],[2,4,6],[3,6,9]])

print("a={}".format(a))
print("a.shape: {}; len(a.shape): {}".format(a.shape, len(a.shape)))

print("b={}".format(b))
print("b.shape: {}; len(b.shape): {}".format(b.shape, len(b.shape)))

print(c)
print("c.shape: {}; len(c.shape): {}".format(c.shape, len(c.shape)))

Output:

a=[1 2 3]
a.shape: (3,); len(a.shape): 1
b=[[1 2 3]]
b.shape: (1, 3); len(b.shape): 2
[[1 2 3]
 [2 4 6]
 [3 6 9]]
c.shape: (3, 3); len(c.shape): 2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.