pandas 填充列表 nan 值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44403116/
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-09-14 03:44:36  来源:igfitidea点击:

Filling list nan values

pythonpandas

提问by Shirohige

How to fill nan values with 0's in a list. I can do it for dataframes but don't know how to do it for lists?

如何在列表中用 0 填充 nan 值。我可以对数据框执行此操作,但不知道如何对列表执行此操作?

listname=listname.fillna(0)

This isn't working.

这不起作用。

回答by piRSquared

You can convert to a pandas series and back to a list

您可以转换为Pandas系列并返回列表

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]

回答by umutto

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]

回答by Exprator

listname1=listname.fillna()

this will work for all int,string,float values

这将适用于所有 int、string、float 值