Get "1" for one-dimensional numpy.array using a curly function

In the function, I give a Numpy array: it can be multidimensional, but also one-dimensional

So, when I give a multidimensional array:

np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]]).shape >>> (3, 4) 

and

 np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]]).shape[1] >>> 4 

Fine

But when I set the form

 np.array([1,2,3,4]).shape >>> (4,) 

and

 np.array([1,2,3,4]).shape[1] >>> IndexError: tuple index out of range 

Ooops, the tuple contains only one element ... so far I want 1 indicate that it is a one-dimensional array. Is there any way to get this? I mean a simple function or method without a discriminant test with ndim for example?

Thanks!

+7
python arrays dimension numpy multidimensional-array
source share
2 answers
 >>> a array([1, 2, 3, 4]) >>> a.ndim 1 >>> b = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]]) >>> b.ndim 2 

If you need a column vector, you can use the .reshape method - in fact, .shape is actually a custom property, so numpy also allows you to do this:

 >>> a array([1, 2, 3, 4]) >>> a.shape += (1,) >>> a array([[1], [2], [3], [4]]) >>> a.shape (4, 1) >>> a.ndim 2 
+8
source share

Hmm, there is no way to set a default for accessing a list item, but you can try:

 >>> shape = np.array([1,2,3,4]).shape >>> shape[1] if shape[1:] else 1 1 

NTN.

0
source share

All Articles