'finding and replacing 'nan' with a number
I want to replace number 3 instead of all 'nan' in array. this is my code:
train= train.replace("nan",int(3))
But nothing changes in my array. Could u please guide me?
Solution 1:[1]
You can use np.isnan:
import numpy as np
train = np.array([2, 4, 4, 8, 32, np.NaN, 12, np.NaN])
train[np.isnan(train)]=3
train
Output:
array([ 2., 4., 4., 8., 32., 3., 12., 3.])
Solution 2:[2]
This code changes all nan to 3:
y = np.nan_to_num(x) + np.isnan(x)*3
This code changes all 3 to nan:
y = x*(x!=3) + 0/(x!=3)
These methods only work with numpy arrays. Please note that np.nan_to_num(x) always changes nan to 0.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Joe T. Boka |
| Solution 2 | SunRazor |
