所以我有一个数据框:
df = pd.DataFrame([["foo","fizz",1],["foo","fizz",2],["foo","buzz",3],["foo","buzz",4],["bar","fizz",6],["bar","buzz",8]],columns=["a","b","c"])
a b c
0 foo fizz 1
1 foo fizz 2
2 foo buzz 3
3 foo buzz 4
4 bar fizz 6
5 bar buzz 8
我可以分组:
df2 = df.groupby(["a","b"]).sum()
c
a b
bar buzz 8
fizz 6
foo buzz 7
fizz 3
这很棒!但是我真正需要的不是“c”列,而是两列,“foo”和“bar”:
foo bar
b
buzz 7 8
fizz 3 6
有人能提供一种方法做到这一点吗?我尝试搜索过,但是可能我没有正确的术语,所以我找不到任何东西。
df2.unstack(level='a')
- Anton Protopopov