'Quick way to access first element in Numpy array with arbitrary number of dimensions?
I have a function that I want to have quickly access the first (aka zeroth) element of a given Numpy array, which itself might have any number of dimensions. What's the quickest way to do that?
I'm currently using the following:
a.reshape(-1)[0]
This reshapes the perhaps-multi-dimensionsal array into a 1D array and grabs the zeroth element, which is short, sweet and often fast. However, I think this would work poorly with some arrays, e.g., an array that is a transposed view of a large array, as I worry this would end up needing to create a copy rather than just another view of the original array, in order to get everything in the right order. (Is that right? Or am I worrying needlessly?) Regardless, it feels like this is doing more work than what I really need, so I imagine some of you may know a generally faster way of doing this?
Other options I've considered are creating an iterator over the whole array and drawing just one element from it, or creating a vector of zeroes containing one zero for each dimension and using that to fancy-index into the array. But neither of these seems all that great either.
Solution 1:[1]
a.flat[0]
This should be pretty fast and never require a copy. (Note that a.flat
is an instance of numpy.flatiter
, not an array, which is why this operation can be done without a copy.)
Solution 2:[2]
You can use a.item(0)
; see the documentation at numpy.ndarray.item
.
A possible disadvantage of this approach is that the return value is a Python data type, not a numpy object. For example, if a
has data type numpy.uint8
, a.item(0)
will be a Python integer. If that is a problem, a.flat[0]
is better--see @user2357112's answer.
Solution 3:[3]
np.hsplit(x, 2)[0]
Source: https://numpy.org/doc/stable/reference/generated/numpy.dsplit.html Source: https://numpy.org/doc/stable/reference/generated/numpy.hsplit.html
Solution 4:[4]
## y -- numpy array of shape (1, Ty)
if you want to get the first element:
use y.shape[0]
if you want to get the second element:
use y.shape[1]
Source: https://docs.scipy.org/doc/numpy/reference/generated/numpy.take.html
You can also use the take for more complicated extraction (to get few elements):
numpy.take(a, indices, axis=None, out=None, mode='raise')[source] Take elements from an array along an axis.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 | |
Solution 4 | sivi |