Python 通过按分组并在列中添加值来展平列
我有一个像Python 通过按分组并在列中添加值来展平列,python,pandas,Python,Pandas,我有一个像 id, index, name, count1, count2 1, 1, foo, 12, 10 1, 2, foo, 11, 12 1, 3, foo, 23, 12 1, 1, bar, 11, 21 ... 2, 1, foo, ... 我想得到一个数据帧,如下所示 id, name, count1, count2 1, foo, 46,34 1, bar, .. 所以基本上,我想从这个字段中“清洗”索引。。在添加count
id, index, name, count1, count2
1, 1, foo, 12, 10
1, 2, foo, 11, 12
1, 3, foo, 23, 12
1, 1, bar, 11, 21
...
2, 1, foo, ...
我想得到一个数据帧,如下所示
id, name, count1, count2
1, foo, 46,34
1, bar, ..
所以基本上,我想从这个字段中“清洗”索引。。在添加count1和count2列时
如何在pandas/python中执行此操作?这就是您想要的吗
In [24]: df.groupby(['id','name']).sum().reset_index()
Out[24]:
id name index count1 count2
0 1 bar 1 11 21
1 1 foo 6 46 34
如果要删除索引
列:
In [26]: df.groupby(['id','name']).sum().reset_index().drop('index', 1)
Out[26]:
id name count1 count2
0 1 bar 11 21
1 1 foo 46 34
数据:
In [25]: df
Out[25]:
id index name count1 count2
0 1 1 foo 12 10
1 1 2 foo 11 12
2 1 3 foo 23 12
3 1 1 bar 11 21