Search code examples
pythonnumpyvectorization

Change values of a numpy array based on certain condition


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 ?


Solution

  • 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.