python - Pandas - 计算和旋转以获得前两年的收入

标签 python pandas dataframe group-by pivot-table

我有一个如下所示的数据框

df = pd.DataFrame(
    {'stud_id' : [101, 101, 101, 101, 
                  101, 102, 102, 102],
     'sub_code' : ['CSE01', 'CSE01', 'CSE01', 
                   'CSE01', 'CSE02', 'CSE02',
                   'CSE02', 'CSE02'],
     'ques_date' : ['10/11/2022', '06/06/2022','09/04/2022', '27/03/2022', 
                '13/05/2010',  '10/11/2021','11/1/2022', '27/02/2022'],
     'revenue' : [77, 86, 55, 90, 
                65, 90, 80, 67]}
)
df['ques_date'] = pd.to_datetime(df['ques_date'])

我想做以下事情

a) 根据我们组织的财政年度日历计算自定义财政年度。也就是说,10 月至 12 月是第 1 季度,1 月至 3 月是第 2 季度,4 月至 6 月是第 3 季度,7 月至 9 月是第 4 季度。

b) 按 Stud_id 分组

c) 计算前两个自定义财政年度的收入总和(从特定日期 = 2022 年 12 月 20 日起)。例如,如果我们处于 2023 财年,我想分别获取客户 2022 财年和 2021 财年的收入总和

所以,我根据这篇文章尝试了以下操作 here

df['custom_qtr'] = pd.to_datetime(df['ques_date'], dayfirst=True).dt.to_period('Q-SEP')
date_1 = pd.to_datetime('20-12-2022') # CUT-OFF DATE
df['custom_year'] = df['custom_qtr'].astype(str).str.extract('(?P<year>\d+)')
df['date_based_qtr']  = date_1.to_period('Q-SEP')
df['custom_date_year'] = df['date_based_qtr'].astype(str).str.extract('(?P<year>\d+)')
df['custom_year'] = df['custom_year'].astype(int)
df['custom_date_year'] = df['custom_date_year'].astype(int)
df['diff'] = df['custom_date_year'].sub(df['custom_year'])
df = df[df['diff'].isin([1,2])]
out_df = df.pivot_table("revenue", index=['stud_id'],columns=['custom_year'],aggfunc=['sum']).add_prefix('rev_').reset_index().droplevel(0,axis=1)

但这会导致输出列不一致,如下所示

enter image description here

我希望我的输出如下所示

enter image description here

更新输出

enter image description here

最佳答案

看来您只需要首先对季度进行细化,过滤以仅包含 2021 年和 2022 年的行,然后汇总并进行数据透视:

(df.assign(
    qyear = pd.to_datetime(df['ques_date'], dayfirst=True).dt.to_period('Q-SEP').dt.qyear
  )[lambda x: x.qyear.isin([2021, 2022])]
  .assign(qyear=lambda x: x.qyear.astype('category').cat.set_categories([2021, 2022]))
  .groupby(['stud_id', 'qyear'])
  .revenue.sum()
  .unstack(level=1)
  .add_prefix('rev_')
  .reset_index(drop=False))

#qyear  stud_id  rev_2021  rev_2022
#0          101         0       231
#1          102         0       157

更新:

df['qyear'] = pd.to_datetime(df['ques_date'], dayfirst=True).dt.to_period('Q-SEP').dt.qyear.astype('category').cat.set_categories([2021, 2022])
df.groupby(['stud_id', 'sub_code', 'qyear']).revenue.sum().unstack(level=1, fill_value=0).add_prefix('rev_').reset_index(drop=False)

sub_code  stud_id qyear  rev_CSE01  rev_CSE02
0             101  2021          0          0
1             101  2022        231          0
2             102  2021          0          0
3             102  2022          0        157

关于python - Pandas - 计算和旋转以获得前两年的收入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74917129/

相关文章:

Python MIT 讲座 : log(n) complexity of the example

python - Web 进程在启动后 60 秒内无法绑定(bind)到 $PORT

python - 两个带有非唯一标签的 Pandas 系列的操作行为是什么?

r - `names(df[1]) <- ` 和 `names(df)[1] <- ` 的区别

rbind char 向量到数据框

python - 从 BaseHTTPHandler 解析 http GET 和 POST 参数?

python-2.7 - Pandas 将列表附加到列名列表

python - 从数据框中选择随机值,以便生成的数据框在 python-pandas 的两列中是唯一的

r - 将选择的列乘以 R 中的另一个选择

python - 查询时间过长时 psycopg2 游标挂起