python - How do I swap one value in an array for another in a different array if a condition is met? - Stack Overflow

admin2025-04-28  2

I would like to swap one array value for the value of a different array in the same corresponding position-- if a condition is met. The condition being: If the value in Matrix A = 1, swap this with the value in that same position of Matrix B.

For example:

Matrix A:
[ [1   0   0   1]
  [0   0   1   0]
  [0   1   0   0]
  [0   1   1   0] ]
    
Matrix B:
[[ 0.7   0.3   0.9   0.2]
  [0.1   0.2   0.5   0.6]
  [0.2   0.8   0.1   0.4]
  [0.6   0.4   0.7   0.2]]

Desired Outcome:
[[ 0.7   0     0      0.2]
  [0     0     0.5    0]
  [0     0.8   0      0]
  [0     0.4   0.7    0]]

This is what I've tried:

for i in range(0,4): 
  for i in range(0,4):
     if (A[i,j] == 1):   
          A[i,j] = B[i,j]
print(A)

I get the following error:

Error: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I know this has to do with the condition depending on a value of 1. How do I reconcile this to see that this is not a 'truth boolean', but the actual value of '1'?

I would like to swap one array value for the value of a different array in the same corresponding position-- if a condition is met. The condition being: If the value in Matrix A = 1, swap this with the value in that same position of Matrix B.

For example:

Matrix A:
[ [1   0   0   1]
  [0   0   1   0]
  [0   1   0   0]
  [0   1   1   0] ]
    
Matrix B:
[[ 0.7   0.3   0.9   0.2]
  [0.1   0.2   0.5   0.6]
  [0.2   0.8   0.1   0.4]
  [0.6   0.4   0.7   0.2]]

Desired Outcome:
[[ 0.7   0     0      0.2]
  [0     0     0.5    0]
  [0     0.8   0      0]
  [0     0.4   0.7    0]]

This is what I've tried:

for i in range(0,4): 
  for i in range(0,4):
     if (A[i,j] == 1):   
          A[i,j] = B[i,j]
print(A)

I get the following error:

Error: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I know this has to do with the condition depending on a value of 1. How do I reconcile this to see that this is not a 'truth boolean', but the actual value of '1'?

Share Improve this question edited Jan 10 at 13:58 John Kugelman 363k69 gold badges553 silver badges597 bronze badges asked Jan 9 at 18:43 user23487612user23487612 614 bronze badges 3
  • 1 one of the for loops wants to be j not both i. – JonSG Commented Jan 9 at 18:52
  • A[i,i] versus A[i}[j] -- that triggers your exception.. – rasjani Commented Jan 9 at 18:56
  • @rasjani - No, it doesn't. What did you mean by that? – Tim Roberts Commented Jan 10 at 19:55
Add a comment  | 

3 Answers 3

Reset to default 1

The key is to use numpy's fancy indexing. If you say A==1, that returns a 2D array with True where the condition is true and False otherwise, and you can use that to "filter" the assignment.

Note that your A array must be floating point, otherwise the assignment will truncate those values to 0.

import numpy as np

A = np.array([[1,0,0,1],[0,0,1,0],[0,1,0,0],[0,1,1,0]],dtype=float)
B = np.array([[0.7,0.3,0.9,0.2],[0.1,0.2,0.5,0.6],[0.2,0.8,0.1,0.4],[0.6,0.4,0.7,0.2]])

A[A==1] = B[A==1]
print(A)

Output:

[[0.7 0.  0.  0.2]
 [0.  0.  0.5 0. ]
 [0.  0.8 0.  0. ]
 [0.  0.4 0.7 0. ]]

For completeness, in the specific case of your array A always containing only zeroes or ones as it does in your example, you can simply multiply A and B:

A *= B

TLDR:

Your code works fine IF:

  • array A is of type float rather than int
  • your inner for loop uses a variable j rather than reusing i

Longer Answer

While the answer by @tim-roberts is the one I would actually use, here is one that is similar in strategy to your attempt.

Note: when you say "swap" I have interpreted that be be a swapping both ways, but if you just want to assign the values from B to A and not alter B that is an easy switch.

NOTE: as @tim-roberts points out, it is super important matrix_a and matrix_b are of the same types otherwise you will get rounded results as their types are cast.

import numpy

matrix_a = numpy.array([
    [1.0, 0.0, 0.0, 1.0],
    [0.0, 0.0, 1.0, 0.0],
    [0.0, 1.0, 0.0, 0.0],
    [0.0, 1.0, 1.0, 0.0]
])
    
matrix_b =numpy.array([
    [0.7, 0.3, 0.9, 0.2],
    [0.1, 0.2, 0.5, 0.6],
    [0.2, 0.8, 0.1, 0.4],
    [0.6, 0.4, 0.7, 0.2]
])

height, witdh = matrix_a.shape

for i in range(height):
    for j in range(witdh):
        if (matrix_a[i,j] == 1.0):
            ## matrix_a[i,j] = matrix_b[i,j]
            matrix_a[i,j], matrix_b[i,j] = matrix_b[i,j], matrix_a[i,j]

print("matrix_a")
print(matrix_a)
print("matrix_b")
print(matrix_b)

giving us:

matrix_a
[
 [0.7 0.  0.  0.2]
 [0.  0.  0.5 0. ]
 [0.  0.8 0.  0. ]
 [0.  0.4 0.7 0. ]
]

matrix_b
[
 [1.  0.3 0.9 1. ]
 [0.1 0.2 1.  0.6]
 [0.2 1.  0.1 0.4]
 [0.6 1.  1.  0.2]
]
转载请注明原文地址:http://www.anycun.com/QandA/1745779823a91185.html