我有一个熊猫数据框架如下:

      itm Date                  Amount 
67    420 2012-09-30 00:00:00   65211
68    421 2012-09-09 00:00:00   29424
69    421 2012-09-16 00:00:00   29877
70    421 2012-09-23 00:00:00   30990
71    421 2012-09-30 00:00:00   61303
72    485 2012-09-09 00:00:00   71781
73    485 2012-09-16 00:00:00     NaN
74    485 2012-09-23 00:00:00   11072
75    485 2012-09-30 00:00:00  113702
76    489 2012-09-09 00:00:00   64731
77    489 2012-09-16 00:00:00     NaN

当我尝试应用一个函数到金额列,我得到以下错误:

ValueError: cannot convert float NaN to integer

我尝试使用数学模块中的.isnan应用一个函数 我已经尝试了pandas .replace属性 我尝试了pandas 0.9中的.sparse data属性 我还尝试了在函数中if NaN == NaN语句。 我也看了这篇文章我如何替换NA值与零在一个R数据框架?同时看一些其他的文章。 我尝试过的所有方法都不起作用或不能识别NaN。 任何提示或解决方案将不胜感激。


当前回答

如果你想为一个特定的列填充NaN,你可以使用loc:

d1 = {"Col1" : ['A', 'B', 'C'],
     "fruits": ['Avocado', 'Banana', 'NaN']}
d1= pd.DataFrame(d1)

output:

Col1    fruits
0   A   Avocado
1   B   Banana
2   C   NaN


d1.loc[ d1.Col1=='C', 'fruits' ] =  'Carrot'


output:

Col1    fruits
0   A   Avocado
1   B   Banana
2   C   Carrot

其他回答

这对我有用,但没人提过。会有什么问题吗?

df.loc[df['column_name'].isnull(), 'column_name'] = 0

填补缺失值的简单方法:-

填充字符串列:当字符串列有缺失值和NaN值时。

df['string column name'].fillna(df['string column name'].mode().values[0], inplace = True)

填充数字列:当数字列有缺失值和NaN值时。

df['numeric column name'].fillna(df['numeric column name'].mean(), inplace = True)

用零填充NaN:

df['column name'].fillna(0, inplace = True)

并不保证切片返回一个视图或副本。你可以这样做

df['column'] = df['column'].fillna(value)

已经有很多贡献了,但因为我是新来的,我仍然会提供意见。

在Pandas DataFrame中有两种方法将NaN值替换为0:

fillna():函数使用指定的方法填充NA/NaN值。 Replace (): df.replace()一个简单的方法,用于替换字符串,正则表达式,列表,字典

例子:

#NaN with zero on all columns
df2 = df.fillna(0)


#Using the inplace=True keyword in a pandas method changes the default behaviour.
    df.fillna(0, inplace = True)

# multiple columns appraoch
df[["Student", "ID"]] = df[["Student", "ID"]].fillna(0)

最后是replace()方法:

df["Student"] = df["Student"].replace(np.nan, 0)

下面的代码适合我。

import pandas

df = pandas.read_csv('somefile.txt')

df = df.fillna(0)