我想编写一个例程,从数组中读取某些元素的值。元素选择被指定为一个数组,其中每一行包含一个元素的索引。该例程应该适用于具有任意数量轴的数组。
我可以想出下面的解决方案,但我不喜欢它,因为转换为元组(或列表)感觉有点不必要,尽管我需要它来防止高级索引。有没有更多的 numpythonic 方法来做到这一点?
import numpy as np
def get_elements(aa, inds):
myinds = tuple(inds.transpose())
return aa[myinds]
AA = np.arange(6)
AA.shape = ( 3, 2 )
inds = np.array([[ 0, 0 ], [ 2, 1 ]])
data2 = get_elements(AA, inds) # contains [ AA[0,0], A[2,1] ]
BB = np.arange(12)
BB.shape = ( 2, 3, 2 )
inds = np.array([[ 0, 0, 0], [ 1, 2, 1 ]])
data3 = get_elements(BB, inds) # contains [ BB[0,0,0], BB[1,2,1] ]
请您参考如下方法:
对于相同的元素,您的 tuple(ind.T) 生成与 np.where 相同的内容。
In [117]: AA=np.arange(6).reshape(3,2)
In [118]: ind=np.array([[0,0],[2,1]])
In [119]: tuple(ind.T)
Out[119]: (array([0, 2]), array([0, 1]))
In [120]: AA[tuple(ind.T)]
Out[120]: array([0, 5])
使用 where 找到这两个值的索引:
In [121]: np.where((AA==0) + (AA==5))
Out[121]: (array([0, 2]), array([0, 1]))
并从文档中复制 where,另一种查找 [0,5] 值的方法:
In [125]: np.in1d(AA.ravel(), [0,5]).reshape(AA.shape)
Out[125]:
array([[ True, False],
[False, False],
[False, True]], dtype=bool)
In [126]: np.where(np.in1d(AA.ravel(), [0,5]).reshape(AA.shape))
Out[126]: (array([0, 2]), array([0, 1]))
所以你的 tuple 是非常好的 numpy 代码。
来自 numpy 索引文档:
Note In Python, x[(exp1, exp2, ..., expN)] is equivalent to x[exp1, exp2, ..., expN]; the latter is just syntactic sugar for the former.
