-1

Have an incoming numpy array which can be 1-d or 2-d. I'm trying to find the number of row using shape property. My calculation x.shape[0] is failing as for 1-d array, it isn't giving (1,6). Any suggestion how to calculate # of row independent of whether the array is 1-d or 2-d?

2-d array:

>>> x4
array([[1, 2, 3],
       [3, 4, 5]])
>>> x4.shape
(2, 3)
>>> row, col = x4.shape

1-d array

>>> x3
array([1, 2, 3, 3, 4, 5])
>>> x3.shape
(6,)
Dibyendu Dey
  • 349
  • 2
  • 16
  • Depending on how you look at it, a 1d array doesn't have rows (or columns) - just elements. `row` and `column` are convenient labels for 2d arrays, but aren't formally part of the `numpy` documentation. – hpaulj Sep 06 '21 at 19:08

3 Answers3

2

You could look at the last dimension's size instead with -1:

>>> x3.shape[-1]
6

>>> x4.shape[-1]
3

However, to get the broadcasted shape for 2D and 1D arrays alike, you might want to unpack the shape and use 1 as the default number of rows:

>>> *r, c = x3.shape
>>> ((r or [1])[0], c)
(1, 6)

>>> *r, c = x4.shape
>>> ((r or [1])[0], c)
(2, 3)

Which means:

  • if the array is 1D, r is an empty list [], which is falsy, so you end up with (r or [1])[0] equal to [1][0], i.e. 1.

  • if the array is 2D, r is a list containing the number of rows as its first element, a non-empty list is truthy, so you end up with r[0].

See extending iterable unpacking for more on this usage of the asterisk * in Python.


An alternative way is to prepend 1 to the shape straight away. Then, extract the last two elements of that tuple. This will return the correct row and column numbers, regardless if it's a 1D- or 2D-array:

>>> ((1,) + x3.shape)[-2:]
(1, 6)

>>> ((1,) + x4.shape)[-2:]
(2, 3)
Ivan
  • 34,531
  • 8
  • 55
  • 100
0

Do you want the last value of the shape?

x1 = np.ones(10)
x1.shape([-1])

x2 = np.ones((10,6))
x2.shape([-1])
0

YOu could use atleast_2d to add a leading dimension:

In [56]: np.atleast_2d(np.arange(3))
Out[56]: array([[0, 1, 2]])
In [57]: _.shape
Out[57]: (1, 3)
In [58]: np.atleast_2d(np.ones((2,3)))
Out[58]: 
array([[1., 1., 1.],
       [1., 1., 1.]])
In [59]: _.shape
Out[59]: (2, 3)

But look at it's code - it hides a dimension test.

    elif ary.ndim == 1:
        result = ary[_nx.newaxis, :]
hpaulj
  • 221,503
  • 14
  • 230
  • 353