Home > other >  How can I judge an array dimension is (p, ) in a if sentence in Python?
How can I judge an array dimension is (p, ) in a if sentence in Python?

Time:11-01

I found in Python there are two ways to represent the dimension of a '1D' array, namely (p, ) and (p, 1), in which 'p' is number of elements in an array. How can I determine if an argument is the former case or the latter case? The following is an example:

import numpy as np
x = np.array([1, 2, 3])
print(x.shape) # (3,)

x2 = np.random.rand(3, 1)
print(x2.shape) # (3, 1)

If I use 'shape[1] to detect whether the argument has the second dimension, there will be an error since the argument might be the first case. How can I determine the argument is the former case without having an error?

CodePudding user response:

You can use ndim:

x.ndim #1
x2.ndim #2

CodePudding user response:

You can use:

len(x.shape) == 1
  • Related