Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find first element of numpy ndarray of unknown shape [duplicate]

Is there an easy way to pull out the first item of an ndarray if you don't know the shape of the array?

For example. Given the following array:

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

>>> [[[ 1  2  3  4]
      [ 5  6  7  8]
      [ 9 10 11 12]]]

I want to get 1 without assuming I know the shape of this array is 1*3*4.

I am also interested in minimizing the memory and cpu requirements of the solution.

like image 492
FGreg Avatar asked Dec 25 '22 09:12

FGreg


1 Answers

You can use .ravel() to get a flattened view of the ndarray and then chain it with [0] to extract the first element, like so -

arr.ravel()[0]

Please note that .flatten() would create a copy, so in terms of memory might not be a great idea, even though it would still give you the right result.

One way to check whether an operation is creating a copy or view is by checking for memory sharing flag with np.may_share_memory, like so -

In [15]: np.may_share_memory(arr.flatten(),arr)
Out[15]: False # Not sharing memory means a copy

In [16]: np.may_share_memory(arr.ravel(),arr)
Out[16]: True # Sharing memory means a view

It seems, one can also use .flat to get a view.


Seems there is an elegant alternative in np.take -

np.take(arr,0) # Input array is arr, 0 is the index position
like image 169
Divakar Avatar answered Feb 16 '23 01:02

Divakar