Given two numpy arrays:
import numpy as np
A = np.array([[0, 5, 0],
[1, 0, 1],
[0, 2, 0]])
B = np.array([[0, 7, 0],
[1, 0, 1],
[0, 1, 0]])
How can I replace elements in A where the same i,j index is greater in B.
I would have thought that this:
A[A < B] = B
Would work, but it doesn't.
Expected result:
[[0, 7, 0],
[1, 0, 1],
[0, 2, 0]]
A simple solution by conditioning B
to give a similarly sized array and then setting from its results:
A[A < B] = B[B > A]
A[A < B]
has a very different shape than B
, so you can't do that assignment. You wanted to do
A[A < B] = B[A < B]
A bit more efficiently, you could say
mask = A < B
A[mask] = B[mask]
Or you could just evaluate the maximum for each element:
A = np.maximum(A, B)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.