gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 03:38:24 25 4
gpt4 key购买 nike

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

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

示例输入数据:

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

输出示例:

<表类="s-表"><头><日>日期 Total_Volcount_Acount_Bcount_c<正文>2019 年 4 月22002019年5月42112019年6月73312019 年 7 月8431

最佳答案

首先,我建议将日期列拆分为两个不同的列 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com