Pandas Groupby到新专栏

发布于 2025-02-13 15:28:06 字数 905 浏览 2 评论 0原文

我有下表

名称
11.1AAAA
11.2BBBB
21.4CCCC
21.6DDDD
30.4EEEE
30.3FFFF

按组ID进行分组:

groupvalue_1name_1通过
我想1.1AAAA1.2BBBB
21.4CCCC1.6DDDDD
30.4EEEE0.3FFFF

现在a解决方案,假设每组只有两行是可以的,但是如果可能的话,我想看到一个超过两个行的解决方案。

I have the following table

GroupValueName
11.1AAAA
11.2BBBB
21.4CCCC
21.6DDDD
30.4EEEE
30.3FFFF

I'd like to transform the table to the following by grouping by the group ID:

GroupValue_1Name_1Value_2Name_2
11.1AAAA1.2BBBB
21.4CCCC1.6DDDDD
30.4EEEE0.3FFFF

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

离不开的别离 2025-02-20 15:28:06

为每个组添加一个计数器,然后取消堆栈:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文