如何使用后缀列旋转数据框?

发布于 2025-01-18 01:24:59 字数 330 浏览 2 评论 0原文

我有一个带有以下结构的熊猫数据框架:

Frame     P_1_x  P_1_y  P_2_x  P_2_y ... P_N_x P_N_y
0         1      9      6      2         4     3 

我想将其转换为:

      x   y
P_1   1   9 
P_2   6   2 
.
.
.
P_N   4   3

有没有有效的方法与熊猫一起做?

我尝试使用pandas.wide_to_long()函数和多索引,但我无法使其在我的情况下起作用。

I have a pandas dataframe with the following structure:

Frame     P_1_x  P_1_y  P_2_x  P_2_y ... P_N_x P_N_y
0         1      9      6      2         4     3 

And I would like to transform it to:

      x   y
P_1   1   9 
P_2   6   2 
.
.
.
P_N   4   3

Is there any efficient way to do it with pandas?

I tried to use the pandas.wide_to_long() function and multi indexing but I couldn't make it work in my case.

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

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

发布评论

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

评论(1

苹果你个爱泡泡 2025-01-25 01:25:00

围绕_拆分列,然后使用展开参数以转换为多索引,然后堆叠多索引列以重新设计:

s = df.set_index('Frame')
s.columns = s.columns.str.rsplit(r'_', 1, expand=True)
out = s.stack(0).droplevel(0)

     x  y
P_1  1  9
P_2  6  2
...
P_N  4  3

Split the columns around _ and use expand parameter to convert to multiindex, then stack the multiindex columns to reshape:

s = df.set_index('Frame')
s.columns = s.columns.str.rsplit(r'_', 1, expand=True)
out = s.stack(0).droplevel(0)

     x  y
P_1  1  9
P_2  6  2
...
P_N  4  3
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文