1

I am looking for a simple pythonic way to get the first element of a numpy array no matter it's dimension. For example:

For [1,2,3,4] that would be 1

For [[3,2,4],[4,5,6]] it would be 3

Is there a simple, pythonic way of doing this?

3
  • arr.ravel()[0], basically flatten it and access the first item. Commented Aug 30, 2019 at 3:27
  • @cs95. That was my first thought, but it could create a copy of the whole thing if the array is not contiguous Commented Aug 30, 2019 at 3:29
  • arr.flat[0] should be enough. Commented Aug 30, 2019 at 3:34

2 Answers 2

4

Using a direct index:

arr[(0,) * arr.ndim]

The commas in a normal index expression make a tuple. You can pass in a manually-constructed tuple as well.

You can get the same result from np.unravel_index:

arr[unravel_index(0, arr.shape)]

On the other hand, using the very tempting arr.ravel[0] is not always safe. ravel will generally return a view, but if your array is non-contiguous, it will make a copy of the entire thing.

A relatively cheap solution is

arr.flat[0]

flat is an indexable iterator. It will not copy your data.

Sign up to request clarification or add additional context in comments.

2 Comments

np.unravel_index(0, arr.shape) is another way of creating that n-d index.
@hpaulj. Thanks. Added. I also found flat
1

Consider using .item, for example:

a = np.identity(3)
a.item(0)
# 1.0

But note that unlike regular indexing .item strives to return a native Python object, so for example an np.uint8 will be returned as plain int.

If that's acceptable this method seems a bit faster than other methods:

timeit(lambda:a.flat[0])
# 0.3602013469208032
timeit(lambda:a[a.ndim*(0,)])
# 0.3502263119444251
timeit(lambda:a.item(0))
# 0.2366882530041039

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.