Reputation: 138
Let's say I have a 2 dimensional array, a function, and a "mask" of specific rows, as below:
my_array = np.array([[0,1],[2,3],[4,5],[6,7]])
my_mask = np.array([0,1,0,1])
my_func = lambda x: x * 2
How can I apply this function to the rows of the the array that are true in the mask? I.e. for the example above, the result would be:
array([[0,1],[4,6],[4,5],[12,14]])
Upvotes: 0
Views: 145
Reputation: 150735
You can use boolean indexing:
mask = my_mask==1
my_array[mask] = my_func(my_array[mask])
Output:
array([[ 0, 1],
[ 4, 6],
[ 4, 5],
[12, 14]])
Upvotes: 1