将DataFrame展平为一行

时间:2018-05-27 21:11:53

标签: python pandas dataframe

我想重新组织以下多行DataFrame,

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

进入这个单行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

感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

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