Reputation: 41
I need to copy elements from one numpy array to another, but only if a condition is met. Let's say I have two arrays:
x = ([1,2,3,4,5,6,7,8,9])
y = ([])
I want to add numbers from x to y, but only if they match a condition, lets say check if they are divisible by two. I know I can do the following:
y = x%2 == 0
which makes y an array of values 'true' and 'false'. This is not what I am trying to accomplish however, I want the actual values (0,2,4,6,8) and only those that evaluate to true.
Upvotes: 1
Views: 2232
Reputation: 51335
You can get the values you want like this:
import numpy as np
x = np.array([1,2,3,4,5,6,7,8,9])
# array([1, 2, 3, 4, 5, 6, 7, 8, 9])
y = x[x%2==0]
# y is now: array([2, 4, 6, 8])
And, you can sum them like this:
np.sum(x[x%2==0])
# 20
Explanation: As you noticed, x%2==0
gives you a boolean array array([False, True, False, True, False, True, False, True, False], dtype=bool)
. You can use this as a "mask" on your original array, by indexing it with x[x%2==0]
, returning the values of x
where your "mask" is True
. Take a look at the numpy
indexing documentation for more info.
Upvotes: 2