【问题标题】:Flatten columns by grouping by and adding values in pandas通过在 pandas 中分组和添加值来展平列
【发布时间】:2016-07-29 04:32:41
【问题描述】:

我有一个类似的数据框

 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 中做到这一点?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    这就是你想要的吗?

    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
    

    【讨论】:

      猜你喜欢
      • 2019-04-14
      • 2018-06-11
      • 1970-01-01
      • 2016-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-20
      • 1970-01-01
      相关资源
      最近更新 更多