Numpy Arrays; How To Replace Elements With Another Array Based On Conditions?
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.
[[0, 7, 0], [1, 0, 1], [0, 2, 0]]
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)
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module