【发布时间】:2020-02-10 11:15:52
【问题描述】:
我的数据框看起来“像”这样:
index name method values
0. A estimated 4874
1. A counted 847
2. A estimated 1152
3. B estimated 276
4. B counted 6542
5. B counted 1152
6. B estimated 3346
7. C counted 7622
8. C estimated 26
...
我想要做的是将每个“名称”的“估计”和“计数”值的总数相加。我尝试像在这段代码中那样使用 pivot_table 来做,但我一次只能为其中一种方法做。有没有办法可以在相同的代码中为这两种方法做到这一点?
count = df.groupby(['name']).apply(lambda sub_df: sub_df\
.pivot_table(index=['method'], values=['values'],
aggfunc= {'values': lambda x: x[df.iloc[x.index['method']=='estimated'].sum()},
margins=True, margins_name == 'total_estimated')
count
我想得到的最后是这样的:
index name method values
0. A estimated 4874
1. A counted 847
2. A estimated 1152
3. A total_counted 847
4. A total_estimated 6026
5. B estimated 276
6. B counted 6542
7. B counted 1152
8. B estimated 3346
9. B total_counted 7694
10. B total_estimated 3622
11. C counted 7622
12. C estimated 26
13. C total_counted 7622
14. C total_estimated 26
...
【问题讨论】:
标签: python pandas indexing pivot-table aggregate