【问题标题】:Hi. How can I add one row for each group in my dataframe?你好。如何为我的数据框中的每个组添加一行?
【发布时间】:2023-01-16 22:33:29
【问题描述】:
我现在的 df 看起来像那样
| Region |
Descript |
Material |
Input |
| UK |
Bottle |
#1 |
500 |
| UK |
Cap |
#5 |
20 |
| India |
Bottle |
#1 |
400 |
| India |
Cap |
#5 |
2 |
想要一个 df2 是这样的:
| Region |
Descript |
Material |
Input |
| UK |
Bottle |
#1 |
500 |
| UK |
Cap |
#5 |
20 |
| UK |
other |
#7 |
NA |
| India |
Bottle |
#1 |
400 |
| India |
Cap |
#5 |
2 |
| India |
other |
#7 |
NA |
我是 python 的新手。也许有一个简单的解决方案或一个已经类似的案例,但我找不到任何东西
【问题讨论】:
标签:
python
pandas
group-by
newrow
【解决方案1】:
您可以使用groupby.tail获取每个组的最后一行,并使用assign对其进行修改,然后将其concat更改为原始DataFrame并在重置时按索引排序:
out = pd.concat([df,
(df.groupby('Region', sort=False, as_index=False).tail(1)
.assign(Descript='other', Material='#7', Input='NA')]
).sort_index(ignore_index=True)
输出:
Region Descript Material Input
0 UK Bottle #1 500
1 UK Cap #5 20
2 UK other #7 NA
3 India Bottle #1 400
4 India Cap #5 2
5 India other #7 NA