How I can i conditionally change the values in a numpy array taking into account nan numbers? How I can i conditionally change the values in a numpy array taking into account nan numbers? python python

How I can i conditionally change the values in a numpy array taking into account nan numbers?


The fact that you have np.nan in your array should not matter. Just use fancy indexing:

x[x>0] = new_value_for_posx[x<0] = new_value_for_neg

If you want to replace your np.nans:

x[np.isnan(x)] = something_not_nan

More info on fancy indexing a tutorial and the NumPy documentation.


to add or subtract to current value then (np.nan not affected)

import numpy as npa = np.arange(-10, 10).reshape((4, 5))print("after -")print(a)a[a<0] = a[a<0] - 2a[a>0] = a[a>0] + 2print(a)

output

[[-10  -9  -8  -7  -6] [ -5  -4  -3  -2  -1] [  0   1   2   3   4] [  5   6   7   8   9]]after -[[-12 -11 -10  -9  -8] [ -7  -6  -5  -4  -3] [  0   3   4   5   6] [  7   8   9  10  11]]