![](/img/trans.png)
[英]Calculate the number of quarters between two ending dates of quarters in Python
[英]Is there a way to subtract two columns containing Quarters and return the integer number of Quarters between them?
我正在根据订阅期限的结束季度进行群组分析(即群组按您的第一份合同的到期季度组织)。
我正在尝试通过从客户最近的到期季度中减去客户群组季度来为我的群组分析创建周期。 换句话说,我想知道从第一个到期季度到最近一个到期季度已经过去了多少个季度。
我试过直接减法
df_cohort = all_time.groupby(['Cohort', 'End Quarter']).agg({'Account Name':'nunique'}) \
.reset_index(drop=False)
df_cohort['period_number'] = (df_cohort['End Quarter'] - df_cohort.Cohort)
df_cohort
这导致 QuarterEnd 值包含我正在寻找的答案(integer 季度差异数)。
Cohort End Quarter Account Name period_number
0 2015Q1 2015Q1 13 <0 * QuarterEnds: startingMonth=12>
1 2015Q1 2015Q3 1 <2 * QuarterEnds: startingMonth=12>
2 2015Q1 2018Q4 1 <15 * QuarterEnds: startingMonth=12>
3 2015Q1 2019Q2 1 <17 * QuarterEnds: startingMonth=12>
4 2015Q1 2019Q3 1 <18 * QuarterEnds: startingMonth=12>
5 2015Q1 2020Q1 3 <20 * QuarterEnds: startingMonth=12>
而我真正想要的是:
Cohort End Quarter Account Name period_number
0 2015Q1 2015Q1 13 0
1 2015Q1 2015Q3 1 2
2 2015Q1 2018Q4 1 15
3 2015Q1 2019Q2 1 17
4 2015Q1 2019Q3 1 18
5 2015Q1 2020Q1 3 20
我从该计算中获得一个简单的 integer 的所有尝试都失败了。 任何帮助将不胜感激!
这可能不是最优雅的方法,但您不必定义日期等等。 我为这个问题做了一个df:
dfq = pd.read_csv(r"C:/users/k_sego/quarter.csv",sep=";")
print(dfq)
看起来像这样
Cohort EndQuarter
0 2015Q1 2015Q1
1 2015Q1 2015Q3
2 2015Q1 2018Q4
3 2015Q1 2019Q2
4 2015Q1 2019Q3
5 2015Q1 2020Q1
我将每个日期列中的季度提取到新列中,并跟踪它们的来源以及年份。 记得转换成数字。
dfq['CohortQ'] = dfq.Cohort.str.slice(5,6)
dfq['EndQuarterQ'] = dfq.EndQuarter.str.slice(5,6)
dfq['CohortYear'] = dfq.Cohort.str.slice(0,4)
dfq['EndQuarterYear'] = dfq.EndQuarter.str.slice(0,4)
cols = dfq.columns.drop(['Cohort','EndQuarter'])
dfq[cols] = dfq[cols].apply(pd.to_numeric, errors='coerce')
现在,年份乘以 4 之间的差是季度数,但是您需要添加年份所在季度之间的差。
dfq['CountQuarters'] = (dfq['EndQuarterYear']-dfq['CohortYear'])*4 +(dfq['EndQuarterQ']-dfq['CohortQ'])
这使
Cohort EndQuarter CohortQ EndQuarterQ CohortYear EndQuarterYear \
0 2015Q1 2015Q1 1 1 2015 2015
1 2015Q1 2015Q3 1 3 2015 2015
2 2015Q1 2018Q4 1 4 2015 2018
3 2015Q1 2019Q2 1 2 2015 2019
4 2015Q1 2019Q3 1 3 2015 2019
5 2015Q1 2020Q1 1 1 2015 2020
CountQuarters
0 0
1 2
2 15
3 17
4 18
5 20
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.