简体   繁体   English

获取多维numpy数组的第一个元素的pythonic方法

[英]pythonic way to get first element of multidimensional numpy array

I am looking for a simple pythonic way to get the first element of a numpy array no matter it's dimension. 我正在寻找一种简单的pythonic方式来获取numpy数组的第一个元素,无论其尺寸如何。 For example: 例如:

For [1,2,3,4] that would be 1 对于[1,2,3,4]将为1

For [[3,2,4],[4,5,6]] it would be 3 对于[[3,2,4],[4,5,6]]它将是3

Is there a simple, pythonic way of doing this? 有没有一种简单的,pythonic的方式来做到这一点?

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 : 您可以从np.unravel_index获得相同的结果:

arr[unravel_index(0, arr.shape)]

On the other hand, using the very tempting arr.ravel[0] is not always safe. 另一方面,使用非常诱人的arr.ravel[0]并不总是安全的。 ravel will generally return a view, but if your array is non-contiguous, it will make a copy of the entire thing. ravel通常会返回一个视图,但是如果数组不连续,它将复制整个对象。

A relatively cheap solution is 一个相对便宜的解决方案是

arr.flat[0]

flat is an indexable iterator. flat是可索引的迭代器。 It will not copy your data. 它不会复制您的数据。

Consider using .item , for example: 考虑使用.item ,例如:

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. 但是请注意,与常规索引不同, .item努力返回本地Python对象,因此,例如, np.uint8将作为纯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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM