[英]Numpy arrays; How to replace elements with another array based on conditions?
Given two numpy arrays:给定两个 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.如何替换 A 中相同 i,j 索引在 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:一个简单的解决方案是通过调节
B
来给出一个类似大小的数组,然后根据其结果进行设置:
A[A < B] = B[B > A]
A[A < B]
has a very different shape than B
, so you can't do that assignment. A[A < B]
的形状与B
非常不同,因此您不能执行该任务。 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.