8

In a function, I give a Numpy array : It can be multi-dimentional but also one-dimentional

So when I give a multi-dimentional 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 ask the shape of

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 contain only one element... while I want 1 to indicate it is a one-dimentional array. Is there a way to get this ? I mean with a simple function or method, and without a discriminant test with ndim for exemple ?

Thanks !

Covich
  • 2,544
  • 4
  • 26
  • 37
  • 1
    possible duplicate of [check if numpy array is multidimensional or not](http://stackoverflow.com/questions/21299798/check-if-numpy-array-is-multidimensional-or-not) – Ashwini Chaudhary Mar 31 '14 at 21:16
  • your array is clearly 1-dim, it wouldn't make sense to ask for its other dimensions. you'd need a matrix such as `np.array([[1,2,3,4]]).shape` (1, 4) – njzk2 Mar 31 '14 at 21:31
  • (or `np.array([[1],[2],[3],[4]]).shape`) – njzk2 Mar 31 '14 at 21:33

2 Answers2

10
>>> 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 wanted a column vector, you can use the .reshape method - in fact, .shape is actually a settable property so numpy also lets you do this:

>>> a
array([1, 2, 3, 4])
>>> a.shape += (1,)
>>> a
array([[1],
       [2],
       [3],
       [4]])
>>> a.shape
(4, 1)
>>> a.ndim
2
wim
  • 338,267
  • 99
  • 616
  • 750
0

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

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

HTH.

Gang Liang
  • 793
  • 1
  • 9
  • 19