python - 如何获得熊猫的滞后月平均值
问题描述
我有这样的数据: 其中 total_percentage_sale 是该时间段内产品的销售百分比。
date. product sale total_percentage_sale
2019-01-01. productA. 12. 30
2019-01-01. productB. 10. 25
2019-02-01. productC. 8. 20
2019-02-01. productD. 10. 25
我想从 total_percentage_sale 列中获得滞后的月平均值。
解决方案
脚步:
- 首先转换
data-type of the
日期。column to
日期时间`。 - 分别提取
year/month
使用.dt.date /.dt.month
。 - 使用提取的值制作所需的组并使用函数聚合
total_percentage_sale
列mean
以获得所需的输出
df['date.'] = pd.to_datetime(df['date.'].str.strip('.'))
df.groupby([df['date.'].dt.year.values , df['date.'].dt.month.values]).agg({'total_percentage_sale' : 'mean'})
输出:
total_percentage_sale
2019 1 27.5
2 22.5
推荐阅读
- angular - Syncfusion 全球化和本地化
- javascript - 即使没有输入,也不允许脚本创建 .txt 文件
- python - python 3运行bash命令获取语法错误
- css - 如何将奇偶行 css 应用于动态加载的组件?
- python - 在 pandas 的多列中排列行值
- spring - spring.data.rest.basePath 未应用
- java - 在进程运行时写入日志文件
- java - 在单元测试中启动新的 JVM
- node.js - 从 Azure AD-OAuth/PassportJS 中的 redirectURL 找不到 404
- python - 在pygame中将玩家移动到鼠标的位置