0

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]])

1 Answer 1

1

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]])
Sign up to request clarification or add additional context in comments.

1 Comment

Or, mask = my_mask.astype(bool).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.