Operation on specific array position based on boolean map, boolean mask

253 Views Asked by At

I want to have the code to do certain operations on the specified elements of the array based on a boolean map.

Let's say I have a numpy array.

a = np.array([[-2.5,-3.2],[2.3,5.3],[1.9,-2.8]])

I want to do certain operations, such as np.ceil() for all the negative elements but not on the positive elements.

I know you could create a boolean mask by doing mask = a<0

However, if you do this np.ceil(a[mask]), this will only output array([-2., -3., -2.])

I want to have the output as array([[-2., -3.], [ 2.3, 5.3], [ 1.9, -2.]])

I know you could write a loop to do this. I am asking for an easier, cleaner solution.

2

There are 2 best solutions below

0
Blast Off Bronze On

You might try something like this. This is one way you can apply the function np.ceil if the number is negative, else just leave it alone.

    result = np.array([
        [
            np.ceil(num) if num < 0 else num
            for num
            in s
        ]
        for s
        in a
    ])

You might also check here Most efficient way to map function over numpy array

1
Ehsan On

One trivial way of doing it is:

a[a<0]=np.ceil(a[a<0])
#array([[-2. , -3. ],
#       [ 2.3,  5.3],
#       [ 1.9, -2. ]])

A better solution, which does not modify a inplace, is to use masked arrays that are constructed for this purpose exactly:

np.ma.ceil(np.ma.masked_greater_equal(a, 0)).data
#array([[-2. , -3. ],
#       [ 2.3,  5.3],
#       [ 1.9, -2. ]])