python - 如何将 groupby 结果分配给 pandas 中的系列
问题描述
我有一个看起来像这样的df:
Date Value
2020 0
2020 100
2020 200
2020 300
2021 100
2021 150
2021 0
我想得到按 where 分组Value
的Date
平均值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
解决方案
这是技巧将不匹配的值替换为缺失值,然后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())
推荐阅读
- javascript - 圆形的圆圈,即一个圆圈中有 6 个圆圈
- scala - Spark Dataframe 实现类似于 Oracle 的 LISTAGG 函数 - 无法在组中订购
- ios - apple-app-site-association 是否适用于 Web 应用程序?
- graphql - Postgraphile - “必须提供查询根”错误消息
- javascript - 为图像的水平轮播创建鼠标滚轮导航选项
- r - 使用 dplyr/tidyr 在 R 中格式化/生成新表
- android - 从 Video.mp4 创建的位图并希望再次显示与视频相同的位图
- android - 如何通过parcelable发送包含列表的列表对象
- android - 片段被视图分页器布局切割
- google-maps - 获取边界框的 TMS 服务的 {X} 和 {Y} 值