Skip to content Skip to sidebar Skip to footer

Find First Element Of Numpy Ndarray Of Unknown Shape

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

Solution 1:

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 # NotsharingmemorymeansacopyIn[16]: np.may_share_memory(arr.ravel(),arr)
Out[16]: True # Sharingmemorymeansaview

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

Solution 2:

The fastest way that I've found so far it to use the item() method:

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

Be aware, though, that it converts the value to a Python object, so the performance might depend on the data type and on which version of Python you are using.

>>> type(arr.item(0))
int

The next fastest is arr.flat[0]. It has the advantage of returning a numpy type.

>>>arr.flat[0]
1
>>>type(arr.flat[0])
numpy.int64

Solution 3:

I would suggest flatten then take element [0]

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]]]

arr.flatten()[0]

>>> 1

Solution 4:

The above answers will work. However, you could also use:

arr.reshape(-1)[0]

Post a Comment for "Find First Element Of Numpy Ndarray Of Unknown Shape"