[英]Filling list nan values
How to fill nan values with 0's in a list. 如何在列表中用0填充nan值。 I can do it for dataframes but don't know how to do it for lists?
我可以为数据帧执行此操作,但不知道如何为列表执行此操作?
listname=listname.fillna(0)
This isn't working. 这不起作用。
You can use list comprehension and check with math.isnan : 您可以使用列表理解并使用math.isnan进行检查:
import math
listname = [0 if math.isnan(x) else x for x in listname]
But that would not work with non float types, if you have strings, other numeric types etc.. in your list then you can use str(x) != 'nan
' 但是这不适用于非浮点类型,如果你的列表中有字符串,其他数字类型等,那么你可以使用
str(x) != 'nan
'
listname = [0 if str(x)=='nan' else x for x in listname]
You can convert to a pandas series and back to a list 您可以转换为熊猫系列并返回列表
pd.Series(listname).fillna(0).tolist()
Consider the list listname
考虑列表
listname
listname = [1, np.nan, 2, None, 3]
Then 然后
pd.Series(listname, dtype=object).fillna(0).tolist()
[1, 0, 2, 0, 3]
listname1=listname.fillna()
这适用于所有int,string,float值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.