查找未知形状numpy的ndarray的第一要素 [英] Find first element of numpy ndarray of unknown shape
问题描述
有一个简单的方法来拉出一个ndarray的第一个项目,如果你不知道数组的形状?
Is there an easy way to pull out the first item of an ndarray if you don't know the shape of the array?
例如。鉴于以下数组:
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]]]
我想获得 1
而不承担我知道这个数组的形状是1 * 3 * 4。
I want to get 1
without assuming I know the shape of this array is 1*3*4.
我也有兴趣在减少解决方案的内存和CPU要求。
I am also interested in minimizing the memory and cpu requirements of the solution.
推荐答案
您可以使用的 .ravel()
得到ndarray的平面视图,然后的链的它 [0]
来提取的第一要素,像这样 -
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]
请注意, .flatten()
将创建一个副本,因此在内存方面可能不是一个好主意,即使它仍然会给你正确的结果。
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.
要检查操作是否正在创建一个复制一个方式
或视图
是通过检查内存分享标志 np.may_share_memory
,像这样 -
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 # Not sharing memory means a copy
In [16]: np.may_share_memory(arr.ravel(),arr)
Out[16]: True # Sharing memory means a view
看来,还可以使用的 .flat
得到一个视图。
It seems, one can also use .flat
to get a view.
似乎没有在 <优雅的替代code> np.take -
Seems there is an elegant alternative in np.take
-
np.take(arr,0) # Input array is arr, 0 is the index position
这篇关于查找未知形状numpy的ndarray的第一要素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!