Python 查找并用数字替换“nan”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33490635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:26:16 来源:igfitidea点击:
finding and replacing 'nan' with a number
提问by Talia
I want to replace number 3 instead of all 'nan' in array. this is my code:
我想替换数组中的数字 3 而不是所有的“nan”。这是我的代码:
train= train.replace("nan",int(3))
But nothing changes in my array. Could u please guide me?
但我的阵列没有任何变化。你能指导我吗?
采纳答案by Raymond Hettinger
>>> 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]
回答by Joe T. Boka
You can use np.isnan
:
您可以使用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.])