估算熊猫均值缺失的组均值

时间:2020-08-25 00:33:34

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

我在这里遇到了类似的问题,但他们没有回答我的问题。如果您发现时间,请提供帮助:

我有一个带有2个变量 'unit'(str), 'leaves_used'(float64)和其他一些变量的数据框。我正在尝试使用组均值为'leaves_used'估算'unit'='Finance'的缺失值。我已经编写了以下代码行,但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

请帮助我纠正此问题!还请说明为什么需要其他解决方案的背后原因,而这并不能使我获得预期的结果

1 个答案:

答案 0 :(得分:0)

这里的问题是,当我们执行链函数时,我们不能使用inplace

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