在 numpy 中使用重复索引时如何指定列 [用于 np.add.at()]

How to specify columns when using repeated indices with numpy [for use with np.add.at()]

我正在尝试将加法运算符应用到一个数组,我希望在该数组中使用重复索引来指示重复的加法运算。从 Python 数据科学书籍 (https://jakevdp.github.io/PythonDataScienceHandbook/02.07-fancy-indexing.html) 中,似乎可以使用 np.add.at(original matrix, indices, thing to add),但我无法弄清楚如何指定对列而不是行进行操作的索引.

例如虚拟示例

# Create Array
A = np.arange(12)
A = A.reshape(4,3)
print(A)

给予

[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]

# Create columns to add to A (in reality, all values won't be the same)
B = np.ones_like(A[:, [0,0]])
print(adder)

给予

[[1 1]
 [1 1]
 [1 1]
 [1 1]]

我想执行操作 A[:, [0, 0]] += B 但使用重复索引表示重复操作的系统(因此在这种情况下,B 的两列都添加到第 0 列)。结果应该是:

[[ 2  1  2]
 [ 5  4  5]
 [ 7  7  8]
 [ 11 10 11]]

我相信这可以使用 np.add.at(A, I, B) 来完成,但是我如何指定索引 I 以对应于 [:, [0,0]] 因为这给出了语法错误(似乎索引矩阵不能包含 : 字符?)。

谢谢

In [12]: A = np.arange(12).reshape(4,3)
In [13]: np.add.at(A, (slice(None), [0,0]), 1)
In [14]: A
Out[14]: 
array([[ 2,  1,  2],
       [ 5,  4,  5],
       [ 8,  7,  8],
       [11, 10, 11]])

这也可以用s_写成

np.add.at(A, np.s_[:, [0,0]], 1)

s_ 是一个 class 对象,它允许我们使用索引符号来创建必要的元组。在索引上下文中 Python 解释器将 : 转换为 slice 对象。

In [19]: np.s_[:, [0,0]]
Out[19]: (slice(None, None, None), [0, 0])