首页 > 解决方案 > 用索引列表替换 3d Numpy 数组的多个值

问题描述

我需要使用索引列表将 3d NumPy 数组的多个值替换为其他值。例如:

old_array = np.full((224,224,3),10)
# in below list first position element are indexes and 2nd one are their corresponding values
list_idx_val = [[array([[ 2, 14,  0],
   [ 2, 14,  1],
   [ 2, 14,  2],
   [99, 59,  1],
   [99, 61,  1],
   [99, 61,  2]], dtype=uint8), array([175, 168, 166,119, 117, 119], dtype=uint8)]
#need to do
old_array[2,14,1] =168

一种方法是简单地访问索引值并用新值替换旧值。但是 NumPy 数组和索引列表非常大。我非常感谢一个快速有效的解决方案(没有循环,最好是切片或其他可能)来替换数组值,因为我需要通过使用这样的索引列表以最小的延迟替换值来创建数千个数组。

标签: pythonarraysnumpyindexing

解决方案


让我们做数组索引:

idx, vals = list_idx_val

old_array[idx[:,0], idx[:,1], idx[:,2]] = vals

输出(plt.show):

在此处输入图像描述


推荐阅读