2

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.

Ehsan
  • 12,072
  • 2
  • 20
  • 33
Chingyuen
  • 21
  • 3

2 Answers2

0

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. ]])
Ehsan
  • 12,072
  • 2
  • 20
  • 33
  • Thank you so much for your answers! Mask is what I was looking for. This relies on the np.ma.ceil function which is provided by NumPy. What if it's a custom user-defined function? Is there a way to map a function to a masked array? – Chingyuen Apr 15 '21 at 09:08
-1

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