【问题标题】:How to flip pandas column names on multi level column flatten如何在多级列展平上翻转熊猫列名
【发布时间】:2021-02-03 06:06:54
【问题描述】:

我有以下数据框,

                       AirPressure...                            WindDirection    
Date       Location1   Location2.......Location8593 Location8594 Location8595
2010-01-01 xxx.        xxx             xxx          xxx.         xxx.                
2010-01-02 xxx.        xxx             xxx          xxx.         xxx.              
2010-01-03 xxx.        xxx             xxx          xxx.         xxx.               
....
2010-01-01 xxx.        xxx             xxx          xxx.         xxx.              
...
2020-10-10 xxx.        xxx             xxx          xxx.         xxx.               

我正在努力使它成为下面的那个。

Date       AirPressure-Location1 SoilMoisture-Location1.....WindDirection-Location8595
2010-01-01 xxx.                  xxx                        xxx
......
2020-10-10 xxx.                  xxx                        xxx

我运行以下命令,

frame.columns = ['-'.join(col).strip() for col in frame.columns.values]

但是我得到了,

Date       Location1-AirPressure Location1-SoilMoisture.....Location8595-WindDirection
2010-01-01 xxx.                  xxx                        xxx
......
2020-10-10 xxx.                  xxx                        xxx

我如何像上面想要的那样翻转名字?

【问题讨论】:

    标签: arrays pandas string dataframe


    【解决方案1】:

    你可以使用f-strings:

    frame.columns = [ f'{b}-{a}' for a, b in frame.columns]
    

    或者通过索引改变列的顺序:

    frame.columns = ['-'.join(col[::-1]).strip() for col in frame.columns]
    

    或者:

    frame = frame.swaplevel(1, 0, axis=1)
    frame.columns = ['-'.join(col).strip() for col in frame.columns]
    

    【讨论】:

    • 使用frame.columns和frame.columns.values有区别吗?
    • @anarchy - 如果使用 frame.columns.values 它将列转换为 numpy 数组,但这不是必需的,因为工作方式与 frame.columns 相同,因此省略,因为简化的解决方案。
    猜你喜欢
    • 2022-01-24
    • 2019-07-21
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 2017-05-23
    • 2020-05-03
    相关资源
    最近更新 更多