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

user528025 picture user528025 · Sep 14, 2012 · Viewed 27.1k times · Source

My array is a 2D matrix and it has numpy.nan values besides negative and positive values:

>>> array
array([[        nan,         nan,         nan, ..., -0.04891211,
            nan,         nan],
   [        nan,         nan,         nan, ...,         nan,
            nan,         nan],
   [        nan,         nan,         nan, ...,         nan,
            nan,         nan],
   ..., 
   [-0.02510989, -0.02520096, -0.02669156, ...,         nan,
            nan,         nan],
   [-0.02725595, -0.02715945, -0.0286231 , ...,         nan,
            nan,         nan],
   [        nan,         nan,         nan, ...,         nan,
            nan,         nan]], dtype=float32)

And I want to replace all the positive numbers with a number and all the negative numbers with another number.

How can I perform that using python/numpy?

(For the record, the matrix is a result of geoimage, which I want to perform a classification)

Answer

Pierre GM picture Pierre GM · Sep 14, 2012

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

x[x>0] = new_value_for_pos
x[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.