使用查找表更改数组值

时间:2018-12-11 16:57:50

标签: python arrays numpy matrix lookup

我有一个numpy的2d整数数组:

a = numpy.array([[1, 1, 2, 2],
                 [0, 1, 2, 2],
                 [1, 3, 2, 3]])

我有一个查找表(元组列表),其中包含原始值和新值:

lookup = [(0, 1), 
          (1, 0), 
          (2, 255)]

我的任务是根据查找表对原始数组进行重新分类: 原始数组中的所有零应变为1,所有零应变为零,所有值== 2应更改为255,其他值应保持不变。预期结果是:

[[0, 0, 255, 255],
 [1, 0, 255, 255],
 [0, 3, 255, 3]]

我尝试了以下解决方案:

for row in lookup:
    original_value = row[0]
    new_value = row[1]
    a[a == original_value] = new_value

但是,我没有得到想要的结果,上述操作的结果是:

[[0, 0, 255, 255],
 [0, 0, 255, 255],
 [0, 3, 255, 3]]

注意result [1,0]为0,但应为1。

是否有方法(嵌套循环除外)使用查找表更改原始数组中的值?

3 个答案:

答案 0 :(得分:1)

我认为这可行:

a = np.array([[1, 1, 2, 2],
             [0, 1, 2, 2],
             [1, 3, 2, 3]])
lookup = [(0, 1), 
          (1, 0), 
          (2, 255)]

result = (a == 0) + (a == 2) * 255 + (a != 1) * (a != 0) * (a != 2) * a

您得到以下结果:

 array([[  0,   0, 255, 255],
        [  1,   0, 255, 255],
        [  0,   3, 255,   3]])

答案 1 :(得分:1)

您可以在'for'循环中复制未修改的数组'a':

a = np.array([[1, 1, 2, 2],
             [0, 1, 2, 2],
             [1, 3, 2, 3]])

lookup = [(0, 1), 
          (1, 0), 
          (2, 255)]

a_copy = np.copy(a)

for row in lookup:
    original_value = row[0]
    new_value = row[1]
    a[a_copy == original_value] = new_value

答案 2 :(得分:1)

您可以这样做:

import numpy as np

a = np.array([[1, 1, 2, 2],
              [0, 1, 2, 2],
              [1, 3, 2, 3]])
lookup = [(0, 1),
          (1, 0),
          (2, 255)]

lookup = np.asarray(lookup)
replacer = np.arange(a.max() + 1)
replacer[lookup[:, 0]] = lookup[:, 1]
result = replacer[a]
print(result)

输出:

[[  0   0 255 255]
 [  1   0 255 255]
 [  0   3 255   3]]