有一个名为 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))