Issue
I want to copy elements from one numpy array to another while also checking condition e.g. if an element of B > 1. So, array A will be:
array([[None, None, None],
[None, [4, 5], None],
[None, None, None]])
and array B:
array([[0, 2, 2],
[2, 2, 0],
[0, 0, 0]])
I need array C to be
array([[None, [2], [2]],
[[2], [2, 4, 5], None],
[None, None, None]])
What is the most efficient way of doing that avoiding loops?
Solution
Use np.where
:
a = np.array([None, [1,2], None])
b = np.array([0,1,2])
np.where(b>0, a, b)
>>array([None, 1, 2], dtype=object)
Alternative - If you want to modify in place, you can also use a boolean mask:
a = np.array([None, [1,2], None])
b = np.array([0,1,2])
m = b > 0
a[m] = b[m]
>>array([None, 1, 2], dtype=object)
Sidenote: arrays are not the best thing for that kind of data (see comments)
Answered By - Tarifazo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.