Home > front end >  python:replace the value of a matrix with another matrix by position
python:replace the value of a matrix with another matrix by position

Time:10-05

Replace the value of 0 in matrix A with the value of the same position in matrix B, and the value of non-zero in A remains unchanged. Pandas/numpy approaches are also acceptable.

A:
0 0 1
0 0 0
1 0 0
B:
0 2 4
2 0 3
4 3 0

The ideal result is:

C:
0 2 1
2 0 3
1 3 0

I need a concise way to handle a similar large matrix.

CodePudding user response:

If you have numpy 2d arrays, use numpy assignment:

A[A != 1] = B

A would be the desired output.

If you want a new matrix C:

C = A.copy()
C[C != 1] = B

CodePudding user response:

One possible solution could be:

import numpy as np


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

b = np.array([[0, 2, 4], [2, 0, 3], [4, 3, 0]])

c = np.where(a == 0, b, a)

print(c)

Output:

[[0 2 1]
 [2 0 3]
 [1 3 0]]

CodePudding user response:

Assuming numpy

You can use numpy.where:

import numpy as np

A = np.array([[0, 0, 1],
              [0, 0, 0],
              [1, 0, 0]])

B = np.array([[0, 2, 4],
              [2, 0, 3],
              [4, 3, 0]])

C = np.where(A==1, A, B)

# OR
# C = np.where(A==0, B, A)

output:

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

NB. I used A==1 to be explicit, but implicit 1/True equality makes it possible to do np.where(A, A, B)

Assuming pandas:

The approach is similar using where

dfA = pd.DataFrame(A)
dfB = pd.DataFrame(B)

dfC = dfA.where(dfA.ne(0), dfB)

# OR
# dfC = dfA.mask(dfA.eq(0), dfB)

output:

   0  1  2
0  0  2  1
1  2  0  3
2  1  3  0
  • Related