合并熊猫行

时间:2020-02-05 21:20:01

标签: python pandas jupyter-notebook sum concatenation

我想在df中合并行,因此每个ID /名称都有一个唯一的行,而其他值则是求和(收入)或串联的(主题和乘积)。

我的df与此类似:

ID   Name   Revenue   Subject   Product
123  John   125       Maths     A
123  John   75        English   B
246  Mary   32        History   B
312  Peter  67        Maths     A
312  Peter  39        Science   C

我想合并行,使输出看起来像这样:

ID   Name   Revenue   Subject        Product
123 John    200       Maths English  A B
246 Mary    32        History        B
312 Peter   106       Maths Science  A C

2 个答案:

答案 0 :(得分:5)

尝试一下:

df.groupby(['ID','Name']).agg(Revenue=('Revenue', 'sum'),
                              Subject=('Subject', " ".join),
                              Product=('Product', " ".join))\
  .reset_index()

输出:

|    |   ID | Name   |   Revenue | Subject       | Product   |
|----|------|--------|-----------|---------------|-----------|
|  0 |  123 | John   |       200 | Maths English | A B       |
|  1 |  246 | Mary   |        32 | History       | B         |
|  2 |  312 | Peter  |       106 | Maths Science | A C       |

答案 1 :(得分:3)

将实用程序功能定义为&使用agg。

def f(x): return ' '.join(list(x))

df.groupby(['ID', 'Name']).agg( 
  {'Revenue': 'sum', 'Subject': f, 'Product': f} 
)