将DataFrame展平为单行 [英] Flatten DataFrame into a single row

查看:237
本文介绍了将DataFrame展平为单行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想重新组织下面的多行DataFrame,

I want to reorganize the following mutli-row DataFrame,

       1          2       3
A  Apple     Orange   Grape
B    Car      Truck   Plane
C  House  Apartment  Garage

进入此单行DataFrame.

into this, single-row DataFrame.

     1_A     2_A    3_A  1_B    2_B    3_B    1_C        2_C     3_C
0  Apple  Orange  Grape  Car  Truck  Plane  House  Apartment  Garage

谢谢您的帮助!

推荐答案

unstack + sort_index进行救援:

v = df.unstack().to_frame().sort_index(level=1).T
v.columns = v.columns.map('_'.join)

v
     1_A     2_A    3_A  1_B    2_B    3_B    1_C        2_C     3_C
0  Apple  Orange  Grape  Car  Truck  Plane  House  Apartment  Garage

这篇关于将DataFrame展平为单行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆