【发布时间】:2021-07-09 06:48:29
【问题描述】:
我有类似的数据框
import pandas as pd
emp_df = pd.DataFrame({'empid':[101,101,101,101,102,102],
'salary':[1000,1000,1500,2000,3000,4000],
'month':['Feb','Mar','Apr','May','Apr','May'],
'year':[2020,2020,2021,2021,2019,2021]})
emp_df
原始数据如下:
我试图得到这样的输出:
到目前为止我得到的是:
方法-1:
t1 = emp_df.groupby(["empid", "year"]).agg(
Total_salary=("salary", "sum")
).reset_index()
t1
t1.pivot_table(columns='year')
方法-2:
t3 = emp_df.groupby(['empid','year']).agg('salary').sum('total').reset_index()
t4 = gp.pivot_table(columns=['empid','year'])
pd.DataFrame(t4.to_records())
基本上我想在这里得到两种类型的输出 -
- 如上图所示,每年(1 月至 12 月)每个 empid 的总和(工资)。
- 其他方法是计算每个 empid w.r.t 财政年度 (APR-MAR) 的总和(工资)。
至少在第一步中,我如何才能正确地表示数据?这两个步骤在 PowerBI 中都很简单,但我想在笔记本上使用相同的逻辑来正确表示输出。
【问题讨论】:
标签: python pandas aggregate pivot-table