Pandas:通过Mode有'index out of bounds'错误来填补缺失的值[英] Pandas: fill in missing values by Mode having 'index out of bounds' error

本文是小编为大家收集整理的关于Pandas:通过Mode有'index out of bounds'错误来填补缺失的值的处理方法,想解了Pandas:通过Mode有'index out of bounds'错误来填补缺失的值的问题怎么解决?Pandas:通过Mode有'index out of bounds'错误来填补缺失的值问题的解决办法?那么可以参考本文帮助大家快速定位并解决问题。

问题描述

假设我有以下 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

我想在 ['Gender','Married','Dependents','Education'] 组中用 Mode 值填写 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')

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

推荐答案

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

别忘了导入 numpy.

本文地址:https://www.itbaoku.cn/post/1727806.html