首页 > 解决方案 > 如何将 groupby 结果分配给 pandas 中的系列

问题描述

我有一个看起来像这样的df:

Date    Value
2020    0
2020    100
2020    200
2020    300
2021    100
2021    150
2021    0

我想得到按 where 分组ValueDate平均值Value > 0。当我尝试时:

df['Yearly AVG'] = df[df['Value']>0].groupby('Date')['Value'].mean()

我得到NaN了值,当我打印上面的行时,我得到了我需要的东西,但有Date列。

Date
2020    200
2021    125

我怎样才能拥有以下内容:

Date    Value    Yearly AVG
2020    0        200
2020    100      200 
2020    200      200
2020    300      200
2021    100      125
2021    150      125    
2021    0        125

标签: pythonpandas

解决方案


这是技巧将不匹配的值替换为缺失值,然后GroupBy.transform用于由聚合值填充的新列:

df['Yearly AVG'] = df['Value'].where(df['Value']>0).groupby(df['Date']).transform('mean')
print (df)
   Date  Value  Yearly AVG
0  2020      0       200.0
1  2020    100       200.0
2  2020    200       200.0
3  2020    300       200.0
4  2021    100       125.0
5  2021    150       125.0
6  2021      0       125.0

详情

print (df['Value'].where(df['Value']>0))
0      NaN
1    100.0
2    200.0
3    300.0
4    100.0
5    150.0
6      NaN
Name: Value, dtype: float64

你的解决方案应该改变:

df['Yearly AVG'] = df['Date'].map(df[df['Value']>0].groupby('Date')['Value'].mean())

推荐阅读