gpt4 book ai didi

python - 替换 NumPy 数组的某些给定索引的最有效方法是什么?

转载 作者:行者123 更新时间:2023-12-04 15:05:58 26 4
gpt4 key购买 nike

我有三个数组,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)

最佳答案

使用zip 分隔xy 索引,然后转换为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)]

关于python - 替换 NumPy 数组的某些给定索引的最有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66101847/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com