2

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?

2
  • are they the same shape? Commented Nov 26, 2013 at 0:29
  • yes, they are the same shape Commented Nov 26, 2013 at 0:30

3 Answers 3

3

Here is a way to do it without changing the value of array1 or array2:

mask = (array2 != 255)
result = array1.copy()
result[mask] += array2[mask]
print(result)
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

If you're not using numpy you can do it fairly quickly with zip in a rather large nested list compression call.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.