这个问题在这里已经有了答案:
NumPy selecting specific column index per row by using a list of indexes
(6 个回答)
去年关闭。
有没有更好的方法从“input_array”和“select_id”中获取“output_array”?
我们可以摆脱range( input_array.shape[0] )
?
>>> input_array = numpy.array( [ [3,14], [12, 5], [75, 50] ] )
>>> select_id = [0, 1, 1]
>>> print input_array
[[ 3 14]
[12 5]
[75 50]]
>>> output_array = input_array[ range( input_array.shape[0] ), select_id ]
>>> print output_array
[ 3 5 50]
最佳答案
您可以使用 numpy.choose
从给定的数组中进行选择它从索引数组(在您的情况下 select_id
)和一组数组(在您的情况下 input_array
)构造一个数组以供选择。但是,您可能首先需要转置 input_array
以匹配尺寸。下面是一个小例子:
In [101]: input_array
Out[101]:
array([[ 3, 14],
[12, 5],
[75, 50]])
In [102]: input_array.shape
Out[102]: (3, 2)
In [103]: select_id
Out[103]: [0, 1, 1]
In [104]: output_array = np.choose(select_id, input_array.T)
In [105]: output_array
Out[105]: array([ 3, 5, 50])
关于按列索引在Numpy数组的每一行中选择一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17074422/