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

      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

其他回答

您还可以使用字典来填充DataFrame中特定列的NaN值,而不是用一些oneValue填充所有DF。

import pandas as pd

df = pd.read_excel('example.xlsx')
df.fillna( {
        'column1': 'Write your values here',
        'column2': 'Write your values here',
        'column3': 'Write your values here',
        'column4': 'Write your values here',
        .
        .
        .
        'column-n': 'Write your values here'} , inplace=True)

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

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

用不同的方法替换不同列中的nan:

   replacement= {'column_A': 0, 'column_B': -999, 'column_C': -99999}
   df.fillna(value=replacement)

你可以使用replace将NaN更改为0:

import pandas as pd
import numpy as np

# for column
df['column'] = df['column'].replace(np.nan, 0)

# for whole dataframe
df = df.replace(np.nan, 0)

# inplace
df.replace(np.nan, 0, inplace=True)

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

填充字符串列:当字符串列有缺失值和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)