Pandas:通过具有'index out of bounds'错误的模式填写缺失值

时间:2017-02-23 00:17:51

标签: python pandas

假设我有以下DataFrame:

Sample=pd.DataFrame({'Gender':['Male','Male','Male','Male','Female','Female','Male','Male'],
          'Married':['No','Yes','Yes','Yes','No','No','Yes','Yes'],
          'Dependents':['1','1','1','0','3+','3+','1','1'],
          'Education':['Not Graduate','Graduate','Graduate','Graduate','Not Graduate','Not Graduate','Graduate','Graduate'],
          'ApplicantIncome':[3596,3717,4166,2400,3333,6000,1234,4567],
          'Credit_History':['1',np.nan,'0','1',np.nan,'1',np.nan,'0']})

    ApplicantIncome   Credit_History   Dependents    Education       Gender   Married
0     3596                 1               1         Not Graduate    Male    No
1     3717               NaN               1         Graduate        Male    Yes
2     4166                 0               1         Graduate        Male    Yes
3     2400                 1               0         Graduate        Male    Yes
4     3333               NaN               3+        Not Graduate    Female  No  
5     6000                 1               3+        Not Graduate    Female  No
6     1234               NaN               1         Graduate        Male    Yes   
7     4567                 0               1         Graduate        Male    Yes

我想在['性别','已婚','家属','教育']小组中填写 NaN 和模式值。

我写了下面的代码:

Sample['Credit_History']=Sample.groupby(['Gender','Married','Dependents','Education']).transform(lambda x:
                     x.fillna(x.mode()[0]))['Credit_History']

弹出一个关于越界的错误消息:

IndexError: ('index out of bounds', 'occurred at index ApplicantIncome')

关于如何修复上面的代码的任何想法?谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用简单的代码来实现您的目标。 df["credithistory"].fillna(df["credithistory"].mode())

别忘了导入numpy。