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.
One trivial way of doing it is:
A better solution, which does not modify
a
inplace, is to use masked arrays that are constructed for this purpose exactly: