我想写一个例程,它从数组中读出某些元素的值。元素选择指定为数组,其中每行包含一个元素的索引。该例程适用于具有任意轴数的数组。
我可以提出下面的解决方案,但我不喜欢它,因为转换为元组(或列表)在某种程度上是不必要的,尽管我需要这样做以防止高级索引。还有更多的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] ]
答案 0 :(得分: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
索引文档:
请注意 在Python中,x [(exp1,exp2,...,expN)]等价于x [exp1,exp2,...,expN];后者只是前者的语法糖。