如何高效地替换NumPy数组中给定的索引?

3
我有三个数组,indicesvaluesreplace_values。我需要循环遍历 indices,将 old_values[indices[i]] 中的每个值替换为 new_values[i]。有没有最快速的方法来完成这个操作?感觉应该可以使用 NumPy 函数或高级切片来加速,而不是正常的 for 循环。
以下代码虽然有效,但比较慢:
import numpy as np

# Example indices and values
values = np.zeros([5, 5, 3]).astype(int)

indices = np.array([[0,0], [1,0], [1,3]])
replace_values = np.array([[140, 150, 160], [20, 30, 40], [100, 110, 120]])

print("The old values are:")
print(values)

for i in range(len(indices)):
    values[indices[i][0], indices[i][1]] = replace_values[i]

print("The new values are:")
print(values)
1个回答

2

使用zipxy索引分离,然后转换为tuple并进行赋值:

>>> values[tuple(zip(*indices))] = replace_values
>>> values

array([[[140, 150, 160],
        [  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0]],

       [[ 20,  30,  40],
        [  0,   0,   0],
        [  0,   0,   0],
        [100, 110, 120],
        [  0,   0,   0]],

       [[  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0]],

       [[  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0]],

       [[  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0]]])

tuple(zip(*indices)) 的返回值:

((0, 1, 1), (0, 0, 3))

由于你的索引本身就是np.array,因此你可以删除zip并使用转置,如@MadPhysicist所指出的:

>>> values[tuple(*indices.T)]

2
tuple(zip(*indices)) 可以更高效地写成 tuple(*indices.T)。这样,您可以从两个数组中创建一个元组,而不是将每个元素转换为 int 对象。 - Mad Physicist

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接