【问题标题】:Pandas: combining header rows of a multiIndex DataFramePandas:组合多索引数据帧的标题行
【发布时间】:2018-05-18 03:24:48
【问题描述】:

假设我有一个如下的 DataFrame:

first   bar       baz       foo
second  one  two  one  two  one  two three
A       1    2    3    4    5    6   7
B       8    9    10   11   12   13  14

我想像这样创建一个新的 DataFrame:

        barone  bartwo  bazone baztwo  fooone footwo foothree
A       1       2       3      4       5      6      7
B       8       9       10     11      12     13     14

可能的代码是什么?

【问题讨论】:

    标签: python pandas multi-index


    【解决方案1】:

    1。使用 Python 3.6+ 更新使用 f-string formatting 和列表理解:

    df.columns = [f'{i}{j}' for i, j in df.columns]
    

    2。使用mapjoin

    df.columns = df.columns.map(''.join)
    

    3。如果您的列具有数字数据类型,请使用mapformat

    df.columns = df.columns.map('{0[0]}{0[1]}'.format) 
    

    输出:

       barone  bartwo  bazone  baztwo  fooone  footwo  foothree
    A       1       2       3       4       5       6         7
    B       8       9      10      11      12      13        14
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-10
      • 1970-01-01
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      • 1970-01-01
      • 2018-08-30
      • 1970-01-01
      相关资源
      最近更新 更多