Change values of a numpy array based on certain condition

Question:

Suppose I have a 1D numpy array (A) containing 5 elements:

A = np.array([ -4.0,  5.0,  -3.5,  5.4,  -5.9])

I need to add 5 to all the elements of A that are lesser than zero. What is the numpy way to do this without for-looping ?

Asked By: your_boy_gorja

||

Answers:

It can be done using mask:

A[A < 0] += 5

The way it works is – the expression A < 0 returns a boolean array. Each cell corresponds to the predicate applied on the matching cell. In the current example:

A < 0  # [ True False  True False  True]  

And then, the action is applied only on the cells that match the predicate. So in this example, it works only on the True cells.

Answered By: Elisha

I found another answer:

A = np.where(A<0, A+5, A)
Answered By: your_boy_gorja
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.