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)
In NumPy, to replace missing values NaN ( np. nan ) in ndarray with other numbers, use np. nan_to_num() or np. isnan() .
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]]) .
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.
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.
Try:
a[a>0] = 1 a[a<0] = -1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With