Python 多维numpy数组中的索引更新

Python 多维numpy数组中的索引更新,python,numpy,Python,Numpy,我正在使用numpy对许多大型数组中的许多值进行计数,并跟踪最大值出现在哪些位置 特别是,假设我有一个“计数”数组: data = numpy.array([[ 5, 10, 3], [ 6, 9, 12], [13, 3, 9], [ 9, 3, 1], ... ]) counts = num

我正在使用numpy对许多大型数组中的许多值进行计数,并跟踪最大值出现在哪些位置

特别是,假设我有一个“计数”数组:

data = numpy.array([[ 5, 10, 3],
                    [ 6, 9, 12],
                    [13, 3,  9],
                    [ 9, 3,  1],
                    ...
                    ])
counts = numpy.zeros(data.shape, dtype=numpy.int)
数据
将发生很大变化,但我希望“计数”反映每个位置出现最大值的次数:

max_value_indices = numpy.argmax(data, axis=1)
# this is now [1, 2, 0, 0, ...] representing the positions of 10, 12, 13 and 9, respectively.
根据我对努比广播的理解,我应该能够说:

counts[max_value_indices] += 1
我希望阵列能够更新:

[[0, 1, 0],
 [0, 0, 1],
 [1, 0, 0],
 [1, 0, 0],
 ...
]
但这会增加
计数中的所有值,从而得出:

[[1, 1, 1],
 [1, 1, 1],
 [1, 1, 1],
 [1, 1, 1],
 ...
]
我还认为,如果我将max_value_索引转换为100x1数组,它可能会起作用:

counts[max_value_indices[:,numpy.newaxis]] += 1
但这只会更新位置0、1和2中的元素:

[[1, 1, 1],
 [1, 1, 1],
 [1, 1, 1],
 [0, 0, 0],
 ...
]
我也很乐意将索引数组转换为0和1的数组,然后每次都将其添加到
计数数组中,但我不确定如何构造它。

您可以使用所谓的(aka):


第一个数组,
np.arange(data.shape[0])
指定行。第二个数组,
np.argmax(数据,轴=1)
指定了列。

我想你的意思一定是
argmax()
,而不是
max()
In [24]: counts[np.arange(data.shape[0]), 
                np.argmax(data, axis=1)] += 1

In [25]: counts
Out[25]: 
array([[0, 1, 0],
       [0, 0, 1],
       [1, 0, 0],
       [1, 0, 0]])