Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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)

like image 351
user528025 Avatar asked Sep 14 '12 12:09

user528025


People also ask

How do you replace NaN values in an array?

In NumPy, to replace missing values NaN ( np. nan ) in ndarray with other numbers, use np. nan_to_num() or np. isnan() .

How can we use conditions in NumPy within an array?

It returns a new numpy array, after filtering based on a condition, which is a numpy-like array of boolean values. For example, if condition is array([[True, True, False]]) , and our array is a = ndarray([[1, 2, 3]]) , on applying a condition to array ( a[:, condition] ), we will get the array ndarray([[1 2]]) .

How does NumPy array deal with NaN values?

To check for NaN values in a Numpy array you can use the np. isnan() method. This outputs a boolean mask of the size that of the original array. The output array has true for the indices which are NaNs in the original array and false for the rest.


2 Answers

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.

like image 180
Pierre GM Avatar answered Jan 30 '23 16:01

Pierre GM


Try:

a[a>0] = 1 a[a<0] = -1 
like image 39
silvado Avatar answered Jan 30 '23 16:01

silvado