我有三个数组,
以下代码虽然有效,但比较慢:
indices
、values
和 replace_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)
tuple(zip(*indices))
可以更高效地写成tuple(*indices.T)
。这样,您可以从两个数组中创建一个元组,而不是将每个元素转换为 int 对象。 - Mad Physicist