finding and replacing 'nan' with a number

2019-02-17 06:28发布

问题:

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?

回答1:

>>> import math
>>> train = [10, float('NaN'), 20, float('NaN'), 30]
>>> train = [3 if math.isnan(x) else x for x in train]
>>> train
[10, 3, 20, 3, 30]


回答2:

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.])