Ed *_*ies 1 python sum concatenation pandas jupyter-notebook
我想合并我的 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
Run Code Online (Sandbox Code Playgroud)
我想合并行,以便输出如下所示:
ID Name Revenue Subject Product
123 John 200 Maths English A B
246 Mary 32 History B
312 Peter 106 Maths Science A C
Run Code Online (Sandbox Code Playgroud)
尝试这个:
df.groupby(['ID','Name']).agg(Revenue=('Revenue', 'sum'),
Subject=('Subject', " ".join),
Product=('Product', " ".join))\
.reset_index()
Run Code Online (Sandbox Code Playgroud)
输出:
| | 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 |
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
64 次 |
| 最近记录: |