代码之家  ›  专栏  ›  技术社区  ›  michael0196

将数据帧展平为一行

  •  2
  • michael0196  · 技术社区  · 7 年前

    我想重新组织下面的多行数据帧,

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

    在这个单行数据帧中。

         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 回复  |  直到 7 年前
        1
  •  4
  •   cs95 abhishek58g    7 年前

    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