[英]Combine and aggregate column values and create new column label in Pandas
I have a dataframe where I would like to combine and aggregate row values in Python我有一个 dataframe 我想在 Python 中组合和聚合行值
Data数据
id type q1 22 q2 22
aa hey 2 1
aa hey_plus 3 6
aa hey_plus_1 2 1
bb hi 1 0
bb hi_1 3 4
Desired期望的
id type q1 22 q2 22
aa hey 7 8
bb hi 4 4
Doing正在做
df.groupby(['q1 22', 'q2 22']).sum()
Any suggestion is appreciated任何建议表示赞赏
Just requires a bit of wrangling to get type
to be what you want, using str.split
.使用str.split
只需要一些争论就可以让type
成为你想要的。
df.groupby(["id", df["type"].str.split("_").str[0]]).sum()
q122 q222
id type
aa hey 7 8
bb hi 4 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.