我正在使用 numpy 计算许多大型数组中的大量值,并跟踪最大值出现在哪些位置。
特别是,假设我有一个“计数”数组:
data = numpy.array([[ 5, 10, 3],
[ 6, 9, 12],
[13, 3, 9],
[ 9, 3, 1],
...
])
counts = numpy.zeros(data.shape, dtype=numpy.int)
data 将发生很大变化,但我希望“counts”反射(reflect)每个位置出现最大值的次数:
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.
根据我对 numpy 广播的理解,我应该可以说:
counts[max_value_indices] += 1
我期望的是要更新的数组:
[[0, 1, 0],
[0, 0, 1],
[1, 0, 0],
[1, 0, 0],
...
]
但是这会增加 counts 中的所有值给我:
[[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
...
]
我还认为,如果我将 max_value_indices 转换为 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 的数组,然后每次都将其添加到 counts 数组中,但我不确定如何构造它。
请您参考如下方法:
你可以使用所谓的advanced integer indexing (又名 Multidimensional list-of-locations indexing ):
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]])
第一个数组,np.arange(data.shape[0]) 指定行。第二个数组 np.argmax(data, axis=1) 指定列。
