python - 如何创建一个财政年度的销售累计计数器?
问题描述
我的 df 看起来像这样。
Policy_No Date
1 10/1/2020
2 20/2/2020
3 20/2/2020
4 23/3/2020
5 18/4/2020
6 30/4/2020
7 30/4/2020
我想创建一个基于财政年度(4月至3月)在不同日期记录的保单的累积计数器
Date Cum count of policies
10/1/2020 1
20/2/2020 3
23/3/2020 4
18/4/2021 1
30/4/2021 3
2021 年 4 月 18 日是新的财政年度,计数器从 0 开始。有人可以帮忙解决这个问题吗?
解决方案
有一个名为cumsum的函数可以做到这一点:
df = pd.DataFrame({"Policy_No":[1,2,3,4,5,6,7],"Date":["10/1/2020","20/2/2020","20/2/2020","23/3/2020","18/4/2020","30/4/2020","30/4/2020"]})
print(df)
#0 1 10/1/2020
#1 2 20/2/2020
#2 3 20/2/2020
#3 4 23/3/2020
#4 5 18/4/2020
#5 6 30/4/2020
#6 7 30/4/2020
df.groupby("Date")["Policy_No"].count().cumsum()
#Date
#10/1/2020 1
#18/4/2020 2
#20/2/2020 4
#23/3/2020 5
#30/4/2020 7
如果您想为每个财政年度执行此操作,我认为您需要为每个财政年度创建一个数据框,使用上述逻辑,最后将它们连接起来:
df = ... #dataframe
year_2020 = pd.to_datetime("01/04/2020")<= df["date"] < pd.to_datetime("01/04/2021")
df_2020 = df.loc[year_2020].groupby("date")["Policy_No"].count().cumsum()
year_2021 = pd.to_datetime("01/04/2021")<= df["date"] < pd.to_datetime("01/04/2022")
df_2021 = df.loc[year_2021].groupby("date")["Policy_No"].count().cumsum()
#concat at the end
df_total = pd.concat((df_2020,df_2021))
当然,如果你不能做年份逻辑(因为有很多),你可以把它放在一个循环中,比如:
def get_financial_dates():
"""
Some function that returns the start and end
of each financial year
"""
return date_start,date_end
df_total = pd.DataFrame() #initial dataframe
for date_start, date_end in get_financial_dates():
idx = date_start <= df["date"] < date_end
df_temp = df.loc[idx].groupby("date")["Policy_No"].count().cumsum()
#concat at the end
df_total = pd.concat((df_total,df_temp))
推荐阅读
- linux - 如何获取远程服务器的内存和cpu使用情况?
- asp.net - nuget 包管理器控制台不工作,包源下拉列表被禁用并且为空
- python - 在处理并发请求的烧瓶应用程序中使用全局变量会产生任何问题吗?
- slack - Zabbix 在发送 Slack 通知时超时,但仍会发送警报
- c# - 为什么要使用接口和抽象而不是抽象?
- templates - 如何在 Zendesk 帮助中心 home_page hbs 模板的某个部分呈现链接?
- c++ - 删除“使用命名空间 std::rel_ops”可以改变行为吗?
- node.js - 如何使用nodejs在mongodb中保存和检索图像
- angular - 升级 Angular 版本 8 ---> 9
- ssl - Synology NAS DSM 我想创建新的 SSL 证书,但总是出现“操作失败。请重新登录并重试”