快速访问具有任意维数的Numpy数组中的第一个元素? [英] Quick way to access first element in Numpy array with arbitrary number of dimensions?
问题描述
我有一个函数,我想快速访问给定 Numpy 数组的第一个(又名第零个)元素,该数组本身可能具有任意数量的维度.最快的方法是什么?
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.
推荐答案
a.flat[0]
这应该很快,而且不需要副本.(请注意,a.flat
是 numpy.flatiter
,不是数组.)
This should be pretty fast and never require a copy. (Note that a.flat
is an instance of numpy.flatiter
, not an array.)
这篇关于快速访问具有任意维数的Numpy数组中的第一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!