简体   繁体   English

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

[英]Python merge two arrays based on specific value

I have two arrays 我有两个数组

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]]

I want to add them together. 我想将它们加在一起。 But I only want to add values from array2 to array1 if the value is not 255. How can I do this? 但是我只想将值从array2添加到array1(如果该值不是255)。我该怎么做?

Here is a way to do it without changing the value of array1 or array2: 这是一种不更改array1或array2的值的方法:

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

in numpy 在numpy中

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

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

If you're not using numpy you can do it fairly quickly with zip in a rather large nested list compression call. 如果您不使用numpy,则可以在相当大的嵌套列表压缩调用中使用zip进行快速处理。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM