在Python中将一条记录拆分为多条记录

发布于 2025-01-13 03:39:33 字数 169 浏览 2 评论 0原文

在python中,如何将这样的数据转换为这样的数据:

1

为这样的数据:

2

In python, how can I convert this data like this :

1

into this data like this:

2

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

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

发布评论

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

评论(2

心房的律动 2025-01-20 03:39:33

您可以使用 np.split(..., 2, axis=1) 将数据帧垂直分成两部分:

new_df = pd.concat([x.T.reset_index(drop=True).T for x in np.split(df.set_index('ID'), 2, axis=1)]).sort_index()

输出:

>>> new_df
    0  1  2
ID         
1   0  1  0
1   1  1  1
2   1  1  0
2   0  0  1
3   1  1  1
3   1  0  1
4   1  0  1
4   0  1  0

You could use np.split(..., 2, axis=1) to split the dataframe vertically into 2 parts:

new_df = pd.concat([x.T.reset_index(drop=True).T for x in np.split(df.set_index('ID'), 2, axis=1)]).sort_index()

Output:

>>> new_df
    0  1  2
ID         
1   0  1  0
1   1  1  1
2   1  1  0
2   0  0  1
3   1  1  1
3   1  0  1
4   1  0  1
4   0  1  0
平生欢 2025-01-20 03:39:33

尝试:

pd.concat([df.iloc[:, i:i+3].set_axis([*'XYZ'], axis=1) 
           for i in range(0,6,3)]).sort_index()

输出:

   X  Y  Z
1  0  1  0
1  1  1  1
2  1  1  0
2  0  0  1
3  1  1  1
3  1  0  1
4  1  0  1
4  0  1  0

Try:

pd.concat([df.iloc[:, i:i+3].set_axis([*'XYZ'], axis=1) 
           for i in range(0,6,3)]).sort_index()

Output:

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