首页 > 解决方案 > 如何在python中更改数据框枢轴的布局

问题描述

我的数据框如下所示

Name | Date | Price | Disc%  
A    | 8/29 | 100.0 | 5  
B    | 8/29 | 88.80 | 6  
A    | 8/30 | 99.0  | 4  
B    | 8/30 | 85.0  | 3  

如果我使用

pd.pivot_table(df, index='name',columns='Date',values=['price','disc']...), 

我得到的顶部标题不同,首先显示价格的所有日期,然后显示折扣的所有日期。

    Price         ||   Disc%  
    ----------------------------------  
    8/29 | 8/30    | 8/29   | 8/30  
A    100 | 99.0    | 5      | 4  
B   88.80|  85.0   | 6      | 3  

我需要一个像下面这样的支点(列 - 顶部的日期)

    8/29           ||   8/30  
    ----------------------------------  
    Price | Disc%  | Price  | Disc%  
A    100  |  5     | 99.0   | 4  
B    88.80|  6     | 85.0   | 3  

Any suggestions appreciated.

请忽略上表中的任何格式错误或列标题

标签: pythonpandaspivot-table

解决方案


利用swaplevels

pivoted.swaplevel(-1,-2, 1).sort_index(axis=1)

Date  8/29         8/30      
     Disc%  Price Disc% Price
Name                         
A        5  100.0     4  99.0
B        6   88.8     3  85.0

推荐阅读