在Python中跨越日历季度的财政季度的收入拆分

时间:2020-05-14 18:52:04

标签: python pandas datetime timedelta

我有按客户,按产品(类型,编号,描述),按“财政季度编号”的销售数据(收入和单位),其中该财政季度对于该公司而言是唯一的,并且不是固定的(即,每个天数完全相同)。

我想(我认为吗?)将每一行“拆分”为两个有效的观察/交易,以将单位和收入的适当份额分配给财政季度所跨过的两个常规日历季度。

我还有一个表(df2),用于将公司的每个财务季度映射到日历的开始和结束日期。

小样:

df1 = pd.DataFrame({'fisc_q_id': ['2013Q1', '2013Q2'], 
                   'cust':['Faux Corp', 'Notaco'], 
                   'prod_id':['ABC-123', 'DEF-456'], 
                   'revenue':[100, 400]})

df2 = pd.DataFrame({'fisc_q_id': ['2013Q1', '2013Q2'], 
                    'fq_start':['2012-07-29', '2012-10-28'], 
                    'fq_end':['2012-10-27', '2013-01-26']})

所需的输出将是四行,每行保留原始的“财政季度ID”,但将添加一列,其中包含适当的日历季度以及该季度的分配收入。

我对这可能如何工作有一些想法,但是我的解决方案-如果我什至可以解决的话-与你们提供的解决方案相比肯定是不明智的。

1 个答案:

答案 0 :(得分:0)

IICU

  #Merge the datframes
df3=df1.merge(df2)
#Coerce dates into datetime
df3.fq_start = pd.to_datetime(df3.fq_start)
df3.fq_end = pd.to_datetime(df3.fq_end)#Calculate the Calender Quarter for strat and end
df3['fq_startquarter'] = pd.PeriodIndex(df3.fq_start, freq='Q')
df3['fq_endquarter'] = pd.PeriodIndex(df3.fq_end, freq='Q')
#Calculate the end date of the first quarter in the date range and hence the day difference on either side of the partition
df3['Qdate'] = df3['fq_start'].dt.to_period("Q").dt.end_time
df3['EndQdate'] = pd.to_datetime(df3['Qdate'], format='%Y-%M-%d')
df3['days1']=(df3['EndQdate']-df3['fq_start']).dt.days+1
df3['days2']=(df3['fq_end']-df3['EndQdate']).dt.days
df3['dys0']=(df3['fq_end']-df3['fq_start']).dt.days
df3.drop(columns=['Qdate','EndQdate'], inplace=True)
#Melt the calculated quarters
df4=pd.melt(df3, id_vars=['fisc_q_id','cust','prod_id','revenue','fq_start','fq_end','days1','days2','dys0'], value_name='CalenderQuarter')
df4.sort_values(by='prod_id', inplace=True)
#Allocate groups to the quarteres to allow allocation of calculated days
df4['daysp']=df4.groupby('prod_id')['CalenderQuarter'].cumcount()+1
#Set conditions and choices and use np.where to conditionally calculate revenue prportions
conditions= (df4['daysp']==1, df4['daysp']==2)
choices=(df4['revenue']*(df4['days1']/df4['dys0']),df4['revenue']*(df4['days2']/df4['dys0']))
df4['revenuep']=np.select(conditions,choices)
#Drop columns not required
df4['revenuep']=np.select(conditions,choices).round(0)

enter image description here

一个。当然有机会使用方法链,以使其高效,快捷。

相关问题