python - 熊猫数据框中每月的计数和累计和
问题描述
我有一个带有两列的 pandas DataFrame:id
和processing_date
.
后者是处理项目 (id) 的日期。
import pandas as pd
# df
id processed_date
324 2016-07-08
A550 2016-07-09
79 2016-08-10
C295 2016-08-10
413 2016-08-11
...
111 2021-11-08
709 2021-11-08
我想绘制一个显示每个月处理的项目数量的图表和一个“在几个月内”的累积图表。由于我有 5 年零 4 个月的数据,我必须有 64 个条目和 64 个数据点才能绘制为条形图或线图。
这是我从这里得到的,但它没有按预期工作:
df['date'] = pd.to_datetime(df['processed_date']) # needed by the nature of the data
df.set_index('date')
df = df.groupby('date')['id'].count() # <- this will stack items per day
df = df.groupby(df.index.month)['id'].count() # <- this will stack items per 12 months, but I have 5 years and 4 months of data, hence 64 different months, not 12.
我怎么能做到这一点?
理想输出:
# df
nb_items_processed cum_sum year_month
2 2 2016-07
3 5 2016-08
...
2 xxx 2021-11
解决方案
从groupby().size()
每月计数开始,然后是不带 groupby 的 cumsum:
out = df.groupby(pd.Grouper(key='processed_date', freq='M')).size().reset_index(name='nb_items_processed')
out['cum_sum'] = out['nb_items_processed'].cumsum()
推荐阅读
- sql - SQL Current month filters comparison
- python-3.x - 从 Tensorflow Keras 检查点重新加载最佳权重
- java - 迭代器指针在列表内意外移动
- c - 有人可以解释为什么包含 fgets 的代码行没有被执行吗?
- dashboard - 我在 cognos 11.1.7 版本上遇到了我的门户页面的问题
- php - 如何在 Docker 容器内使用 RabbitMQ 消息(在 Windows 主机上运行)?
- python - 在路径 Django 的 URL 参数中指定两个参数
- solr - 拼写检查需要 Solr 手册以外的指导
- ansible-awx - Ansible AWX/Tower 创建仅限于组的库存
- python - 模型字段的 Django 时间差总和