代码之家  ›  专栏  ›  技术社区  ›  user1471980

如何在pandas中按降序对Date中的列名进行排序

  •  0
  • user1471980  · 技术社区  · 7 月前

    我有这个DataFrame:

    Node      Interface    Speed   Band_In  carrier     Date            
    Server1   wan1         100     80       ATT         2024-05-09
    Server1   wan1         100     50       Sprint      2024-06-21
    Server1   wan1         100     30       Verizon     2024-07-01  
    Server2   wan1         100     90       ATT         2024-05-01
    Server2   wan1         100     88       Sprint      2024-06-02
    Server2   wan1         100     22       Verizon     2024-07-19 
    

    我需要将日期字段转换为这种格式——5月1日、6月2日、7月19日,按降序将它们放在每一列上。在这里看起来像这样:

      Node      Interface    Speed   Band_In  carrier     1-July 9-May  21-Jun          
        Server1   wan1         100     80       ATT        80    50     30    
    

    我试过这个:

    df['Date'] = pd.to_datetime(df['Date']).dt.strftime('%d-%b')
    df['is'] = df['Band_In'] / df['Speed'] * 100
    df = df.pivot_table(index=['Node', 'Interface', 'carrier'], columns='Date', values='is').reset_index()
    

    我需要将列名中的日期值按降序排列为9-May 21 Jun 1-July。

    你知道怎么做吗?

    1 回复  |  直到 7 月前
        1
  •  2
  •   mozway    7 月前

    在以下日期之前,不要将日期转换为字符串 pivot_table ,所以可以很容易地做到 rename :

    df['Date'] = pd.to_datetime(df['Date'])
    df['is'] = df['Band_In'] / df['Speed'] * 100
    
    out = (df.pivot_table(index=['Node', 'Interface', 'carrier'],
                          columns='Date', values='is')
             .rename(columns=lambda x: x.strftime('%-d-%b'))
             .reset_index().rename_axis(columns=None)
          )
    

    输出:

          Node Interface  carrier  1-May  9-May  2-Jun  21-Jun  1-Jul  19-Jul
    0  Server1      wan1      ATT    NaN   80.0    NaN     NaN    NaN     NaN
    1  Server1      wan1   Sprint    NaN    NaN    NaN    50.0    NaN     NaN
    2  Server1      wan1  Verizon    NaN    NaN    NaN     NaN   30.0     NaN
    3  Server2      wan1      ATT   90.0    NaN    NaN     NaN    NaN     NaN
    4  Server2      wan1   Sprint    NaN    NaN   88.0     NaN    NaN     NaN
    5  Server2      wan1  Verizon    NaN    NaN    NaN     NaN    NaN    22.0