【问题标题】:imputing group mean for missing values in Pandas为 Pandas 中的缺失值估算组平均值
【发布时间】:2020-08-25 00:33:34
【问题描述】:

我在这里遇到过类似的问题,但他们没有回答我的问题。如果你有时间请帮忙:

我有一个包含 2 个变量 'unit'(str), 'leaves_used'(float64) 和其他一些变量的数据框。我试图用组平均值为'unit'='Finance' 估算'leaves_used' 的缺失值。我已经编写了以下代码行,但 NaN 没有被替换。你能告诉我需要改变什么,或者这是否是正确的程序?注意:我使用Ipython.core.Interactiveshell 是为了避免编写多个print() 命令

finance_mean=hr.groupby('unit').get_group('Finance')['leaves_used'].mean()
#This correctly computes the mean for the group
hr.loc[(hr['unit']=='Finance') & (hr['leaves_used'].isna()),:]
#This returns the sliced DataFrame for visual inspection which, in my case is one row
hr.loc[hr['unit']=='Finance', 'leaves_used'].replace(np.nan, finance_mean,inplace=True)
#This is running without error so I was assuming the mean replacement is being done
hr.loc[(hr['unit']=='Finance') & (hr['leaves_used'].isna()),:]
# This is to return the sliced dataframe again as before and I see that the NaN has not changed

请帮我纠正这个问题!还请解释为什么需要不同的解决方案背后的原因,这并没有得到我想要的结果

【问题讨论】:

    标签: python-3.x pandas pandas-groupby missing-data


    【解决方案1】:

    这里的问题,当我们做链功能时,我们不能使用inplace

    hr.loc[(hr['unit']=='Finance') & (hr['leaves_used'].isna()),'leaves_used'] = finance_mean
    

    【讨论】:

      猜你喜欢
      • 2019-08-16
      • 1970-01-01
      • 2017-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-19
      • 2020-06-07
      相关资源
      最近更新 更多