Python根据特定值合并两个数组

时间:2013-11-26 00:28:54

标签: python arrays numpy

我有两个数组

array1 = [[ 37.06853867  30.22016525  24.13002205  23.74543762  28.23823929
   29.85162544]
 [ 36.39044189  27.74254036  20.38976479  21.59453011  30.35881233
   34.24060822]
 [ 34.39845657  26.73529243  22.30514145  27.13420486  38.91122437
   48.05885315]
 [ 38.22272491  40.40032578  43.52813721  47.13837051  54.32110977
   64.78022003]
 [ 47.3240242   57.3037529   62.097332    62.22722626  62.09951782
   64.59619141]
 [ 29.9451561   37.32279587  41.77493668  45.76233673  49.91016388
   53.55546951]]


array2 = [[255 255 255 255 255 255]
 [255 255   1 1 255 255]
 [255 255 255 1 255 255]
 [255 255 255 255 255 255]
 [255 255 255 255 255 255]
 [255 255 255 255 255 255]]

我想将它们加在一起。但是我只想将数值从array2添加到array1,如果值不是255.我该怎么做?

3 个答案:

答案 0 :(得分:3)

这是一种在不更改array1或array2的值的情况下执行此操作的方法:

mask = (array2 != 255)
result = array1.copy()
result[mask] += array2[mask]
print(result)

答案 1 :(得分:1)

in numpy

#convert to numpy if necessary 
array2 = np.array(array2)
array1 = np.array(array1)

#then it is easy
array2[array2 == 255] = 0
array1 += array2

答案 2 :(得分:1)

如果您没有使用numpy,可以使用zip在相当大的嵌套列表压缩调用中快速完成。

[[c1 if c2 == 255 else c1 + c2 for c1, c2 in zip(row1, row2)] 
      for row1, row2 in zip(array1, array2)]