【发布时间】:2017-02-06 14:46:57
【问题描述】:
我有一个如下的数据框:
ref, type, amount
001, foo, 10
001, foo, 5
001, bar, 50
001, bar, 5
001, test, 100
001, test, 90
002, foo, 20
002, foo, 35
002, bar, 75
002, bar, 80
002, test, 150
002, test, 110
这就是我想要得到的:
ref, type, amount, foo, bar, test
001, foo, 10, 15, 55, 190
001, foo, 5, 15, 55, 190
001, bar, 50, 15, 55, 190
001, bar, 5, 15, 55, 190
001, test, 100, 15, 55, 190
001, test, 90, 15, 55, 190
002, foo, 20, 55, 155, 260
002, foo, 35, 55, 155, 260
002, bar, 75, 55, 155, 260
002, bar, 80, 55, 155, 260
002, test, 150, 55, 155, 260
002, test, 110, 55, 155, 260
所以我有这个:
df.groupby('ref')['amount'].transform(sum)
但是我如何过滤它以使上述内容仅适用于 type=foo 或 bar 或 test 的行?
【问题讨论】:
-
@EdChum 是的,我可以过滤数据框,但我需要三个新列,其中 ref 和 type 的总和为“amount”。如果这有意义?
-
那么为什么不在 ref 上进行 groupby 然后输入呢?
-
我可以对 ref 和 type 进行分组,但列如何工作?因为我想要每个类型值的总和。
-
我想我误解了你所追求的,你需要使用
map或merge与原始 df 的结果聚合
标签: python pandas merge group-by sum