python - 根据日期范围按类别计算总发生次数和发生次数

标签 python pandas datetime

在下表中,开始日期和结束日期表示计算唯一标识符的时间段。我的目标是计算唯一标识符落在日期之间的次数,但每月显示一次。我还想计算某个类别在该日期范围内的次数。

我是处理表数据和 Pandas 的新手,所以我有点不知所措。非常感谢您的帮助。

示例输入数据:

<表类="s-表"> <头> 开始日期 结束日期 唯一标识符 类别 <正文> 2019-04-17 2020-04-17 编号 1234 一个 2019-05-20 2021-04-03 编号 3492 B 2019-05-20 2021-04-03 编号7376 C 2019-04-18 2021-04-03 编号 9813 一个 2019-06-20 2021-04-03 编号6342 一个 2019-06-20 2021-04-03 编号 6455 B 2019-07-20 2021-04-03 编号6342 一个 2019-06-20 2021-04-03 编号 6455 B 等... 等... 等... 等...

输出示例:

<表类="s-表"> <头> <日>日期 Total_Vol count_A count_B count_c <正文> 2019 年 4 月 2 2 0 0 2019年5月 4 2 1 1 2019年6月 7 3 3 1 2019 年 7 月 8 4 3 1

最佳答案

首先,我建议将日期列拆分为两个不同的列 yearmonth 以便您可以按它们分组。

df = (pd.DataFrame(records, columns=['start', 'end', 'id', 'cat'])
         .astype({'start':'datetime64', 'end':'datetime64'})
         .assign(year=lambda x: x['start'].dt.year)
         .assign(month=lambda x: x['start'].dt.month))

enter image description here

然后可以将cat列分解,方便计算

df_cats = (pd
 .get_dummies(df['cat'], prefix='count')
 .assign(total = lambda r: r['count_A']+r['count_B']+r['count_C']))

你会得到

enter image description here

现在你只需要合并两个 dfs 并使用 groupby.sum() 得到结果

pd.merge(df, df_cats, left_index=True, right_index=True).groupby(['year', 'month'].sum()

你最终会得到

enter image description here

关于python - 根据日期范围按类别计算总发生次数和发生次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66510748/

相关文章:

python - 有没有办法在 venv/web 服务器中安装 Tesseract OCR?

python - 如何在 .txt 文件中的一组下一行单词中的点之后下一行

python - 从多索引 pandas 数据框中引用 pandas 系列值

python - 如何在 Pandas 数据框中拆分文档并为每个句子创建行

PHP/MySql - DateTime 检测是否已分配值?

php DateTime diff - 包括范围内的两个日期?

c# - 在 C# 中获取实际日期时间而不是系统日期时间

python - 使用python将十六进制转为字符串

python - 我的 thrift ./configure 不构建 python 库

python - 使用 pandas.IntervalIndex 作为数据帧索引