标签: numpy-indexing

添加由另一个数组索引的数组的重复元素

我有一个相对简单的问题,如果不使用循环就无法解决。我很难找出这个问题的正确标题。假设我们有两个 numpy 数组:

array_1 = np.array([[0, 1, 2],
                    [3, 3, 3],
                    [3, 3, 4],
                    [3, 6, 2]])

array_2 = np.array([[0, 0, 0], 
                    [1, 1, 1],
                    [2, 2, 2],
                    [3, 3, 3],
                    [4, 4, 4],
                    [5, 5, 5],
                    [6, 6, 6]])
Run Code Online (Sandbox Code Playgroud)

array_1array_2表示我们想要的行的索引sum。例如, array4中的第 行result应包含与array_1 中的所有行array_2具有相同行索引的所有行的总和。3

在代码中更容易理解:

result = np.empty(array_2.shape)

for i in range(array_1.shape[0]):
    for j in range(array_1.shape[1]):
        index = array_1[i, j]
        result[index] = result[index] + array_2[i]
Run Code Online (Sandbox Code Playgroud)

结果应该是:

[[ 0  0 …
Run Code Online (Sandbox Code Playgroud)

python numpy numpy-indexing numpy-ndarray

2
推荐指数
1
解决办法
187
查看次数

标签 统计

numpy ×1

numpy-indexing ×1

numpy-ndarray ×1

python ×1