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, ..

所以基本上,我想从这个字段中“冲走”索引..同时添加 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

如果您想删除index列:

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

关于python - 通过在 pandas 中分组和添加值来展平列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38646160/

相关文章:

python - PySPark - 确定操作后数据类型的函数

Python:日期/时间格式

Python截取屏幕截图并将其保存到缓冲区

python - 与Joblib并行训练sklearn模型会阻止该过程

Python伪逆和向量的行列式

python - 导入错误:C 扩展:没有名为 'parsing' 的模块未构建

python - 如果已经存在,则返回类实例而不是创建新实例

python - 通过 4 的项目数量错误,使用正则表达式提取时放置意味着 1

python - 如果一行不存在,请在 Python 中相应地检查并赋予一个值

python - 如何通过移位和条件找到最大值?