【问题标题】:efficiently flatten multiple columns into a single row in pandas在 pandas 中有效地将多列展平为单行
【发布时间】:2021-11-26 19:57:04
【问题描述】:

如何有效地将数据帧的多列“扁平化”为一行?

A B
1 'a' 'b'
2 'c' 'd'

收件人:

A_1 A_2 B_1 B_2
'a' 'c' 'b' 'd'

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    DataFrame.unstack创建Series with MultiIndex,转换为DataFrame并转置,最后展平MultiIndex

    df = df.unstack().to_frame().T
    df.columns = df.columns.map(lambda x: f'{x[0]}_{x[1]}')
    print (df)
       A_1  A_2  B_1  B_2
    0  'a'  'c'  'b'  'd'
    

    【讨论】:

      猜你喜欢
      • 2020-03-30
      • 1970-01-01
      • 1970-01-01
      • 2016-11-07
      • 2012-10-05
      • 1970-01-01
      • 1970-01-01
      • 2018-06-07
      • 2020-11-21
      相关资源
      最近更新 更多