[英]pandas groupby to new columns
I have the following table我有下表
Group![]() |
Value![]() |
Name![]() |
---|---|---|
1 ![]() |
1.1 ![]() |
AAAA ![]() |
1 ![]() |
1.2 ![]() |
BBBB ![]() |
2 ![]() |
1.4 ![]() |
CCCC![]() |
2 ![]() |
1.6 ![]() |
DDDD ![]() |
3 ![]() |
0.4 ![]() |
EEEE![]() |
3 ![]() |
0.3 ![]() |
FFFF ![]() |
I'd like to transform the table to the following by grouping by the group ID:我想通过按组 ID 分组将表格转换为以下内容:
Group![]() |
Value_1![]() |
Name_1![]() |
Value_2![]() |
Name_2![]() |
---|---|---|---|---|
1 ![]() |
1.1 ![]() |
AAAA ![]() |
1.2 ![]() |
BBBB ![]() |
2 ![]() |
1.4 ![]() |
CCCC![]() |
1.6 ![]() |
DDDDD ![]() |
3 ![]() |
0.4 ![]() |
EEEE![]() |
0.3 ![]() |
FFFF ![]() |
For now a solution, assuming there are only two rows per group is fine, but if possible I'd like to see a solution with more than two rows.现在一个解决方案,假设每组只有两行是好的,但如果可能的话,我希望看到一个超过两行的解决方案。
Adding a counter for each group and then unstack:为每个组添加一个计数器,然后取消堆叠:
df_wide = (df.assign(count=(df.groupby("Group").cumcount() + 1).astype(str))
.set_index(["Group", "count"])
.unstack("count")
.sort_index(axis=1, level=1))
df_wide.columns = df_wide.columns.map('{0[0]}_{0[1]}'.format)
df_wide
Name_1 Value_1 Name_2 Value_2
Group
1 AAAA 1.1 BBBB 1.2
2 CCCC 1.4 DDDD 1.6
3 EEEE 0.4 FFFF 0.3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.