【问题标题】:Flatten DataFrame into a single row将 DataFrame 展平为单行
【发布时间】:2018-05-27 21:11:52
【问题描述】:

我想重组下面的多行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

感谢您的帮助!

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-13
      • 2019-04-06
      • 1970-01-01
      • 2018-12-11
      • 2021-06-02
      • 2021-05-07
      • 2022-09-22
      • 2016-11-07
      相关资源
      最近更新 更多