Joshua
Joshua

Reputation: 2479

Conditionally Replace Elements of an Array Depending on the Contents of Another Array

I am trying to implement the iRPOP- learning algorithm for neural networks. I am using numpy for performance reasons. One important optimization requires conditionally zeroing out elements of an float array based on the contents of a boolean array. The equivalent python code would be:

for index, condition in enumerate(boolean_array):
    if condition:
        float_array[index] = 0

Is there any way to efficiently do this with numpy?

Upvotes: 0

Views: 96

Answers (1)

DSM
DSM

Reputation: 353509

You could use float_array[boolean_array] = 0:

In [2]: boolean_array = np.array([True, False, False, True])

In [3]: float_array = np.ones(4) * 1.0

In [4]: float_array
Out[4]: array([ 1.,  1.,  1.,  1.])

In [5]: float_array[boolean_array] = 0

In [6]: float_array
Out[6]: array([ 0.,  1.,  1.,  0.])

Upvotes: 3

Related Questions