无法在 Pandas 数据框中用零填充 NaN
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/21801507/
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
Cannot Fill NaN with zeros in a Pandas Dataframe
提问by prre72
I have the following problem: I am reading a csv file with missing values by using
我有以下问题:我正在读取一个缺少值的 csv 文件,方法是使用
pd.read_csv(f_name, sep=sep, header=hdr, parse_dates=True, index_col=date_col, quotechar=quote)
pd.read_csv(f_name, sep=sep, header=hdr, parse_dates=True, index_col=date_col, quotechar=quote)
The dataframe I get has 'nan's in it (I was expecting 'NaN's with the Upper cases). Now if I try to replace those nan's with zerosby using
我得到的数据帧中有 'nan's(我期待 'NaN's with the Upper case)。现在,如果我尝试使用 zerosby 替换那些 nan
df.fillna(0)
my df doesn't change (I still see nan's in it) My guess is that fillna is not working because I have nan (lowercase) instead of NaN (uppercase). Am I correct? If yes, do you have an idea why pd.read.csv returns a dataframe with lowercase nan's? I am using Python 2.7.6 (Anaconda bundle)
我的 df 没有改变(我仍然看到里面有 nan)我的猜测是 fillna 不起作用,因为我有 nan(小写)而不是 NaN(大写)。我对么?如果是,您知道为什么 pd.read.csv 返回一个带有小写 nan 的数据框吗?我正在使用 Python 2.7.6(Anaconda 包)
Many thanks for your help.
非常感谢您的帮助。
回答by unutbu
df.fillna(0)returns a new dataframe; it does not alter df.
df.fillna(0)返回一个新的数据帧;它不会改变df。
So instead use:
所以改为使用:
df = df.fillna(0)           # assigns df to a new dataframe

