数组元素作为索引的矢量化更新

数组元素作为索引的矢量化更新

本文介绍了使用另一个 numpy 数组元素作为索引的矢量化更新 numpy 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让 A、C 和 B 是具有相同行数的 numpy 数组.我想更新 A[0] 的第 0 个元素,A[1] 的第 2 个元素等.也就是说,将 A[i] 的第 B[i] 个元素更新为 C[i]

Let A,C and B be numpy arrays with the same number of rows.I want to update 0th element of A[0], 2nd element of A[1] etc. That is, update B[i]th element of A[i] to C[i]

import numpy as np
A = np.array([[1,2,3],[3,4,5],[5,6,7],[0,8,9],[3,7,5]])
B = np.array([0,2,1,2,0])
C = np.array([8,9,6,5,4])
for i in range(5):
A[i, B[i]] = C[i]
print ("FOR", A)
A = np.array([[1,2,3],[3,4,5],[5,6,7],[0,8,9],[3,7,5]])
A[:,B[:]] = C[:]
print ("Vectorized, A", A)

输出:

FOR [[8 2 3]
[3 4 9]
[5 6 7]
[0 8 5]
[4 7 5]]
Vectorized, A [[4 6 5]
[4 6 5]
[4 6 5]
[4 6 5]
[4 6 5]]

for 循环和向量化给出了不同的结果.我不确定如何使用 Numpy 将此 for 循环向量化.

The for loop and vectorization gave different results. I am unsure how to vectorize this for loop using Numpy.

推荐答案

您的方法不起作用的原因是您将整个 B 作为列索引传递并将它们替换为C 相反,您需要同时指定行索引和列索引.由于您只想更改前 4 行,您可以简单地使用 np.arange(4) 选择行 B[:4] 列和 C[:4] 替换项.

The reason that your approach doesn't work is that you're passing the whole B as the column index and replace them with C instead you need to specify both row index and column index. Since you just want to change the first 4 rows you can simply use np.arange(4) to select the rows B[:4] the columns and C[:4] the replacement items.

In [26]: A[np.arange(4),B[:4]] = C[:4]

In [27]: A
Out[27]:
array([[8, 2, 3],
       [3, 4, 9],
       [5, 6, 7],
       [0, 8, 5],
       [3, 7, 5]])

请注意,如果您想更新整个数组,如@Warren 的评论中所述,您可以使用以下方法:

Note that if you wanna update the whole array, as mentioned in comments by @Warren you can use following approach:

A[np.arange(A.shape[0]), B] = C

这篇关于使用另一个 numpy 数组元素作为索引的矢量化更新 numpy 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 09:58