【问题标题】:sorting pandas dataframe by column alphabetically after first 4 characters在前 4 个字符后按字母顺序对 pandas 数据帧进行排序
【发布时间】:2021-10-15 00:25:32
【问题描述】:

我有一个这样的数据框

    new_col    new_elements       new_val     old_col   old_elements   old_val
 0  0          384444683          593         2         423483819      480
 1  1          384444684          594         32        248239340      341
 2  2          384444686          596         0         249289049      342

我想要这个:

    new_col    old_col   new_elements      old_elements     new_val     old_val   
 0  0          2         384444683         423483819        593         480     
 1  1          32        384444684         248239340        594         341
 2  2          0         384444686         249289049        596         342

我知道df.sort_index(axis=1) 会按字母顺序对我的列进行排序,但它们现在已经按这种方式排序了。我想要的是让它们在前缀(前 4 个字符)之后按字母顺序排序

【问题讨论】:

    标签: python python-3.x pandas jupyter


    【解决方案1】:
    col = df.columns
    col = sorted(col,key=lambda x: x[4:])
    col
    df = df[col]
    df
    

    总之df = df[sorted(df.columns,key=lambda x: x[4:])]

    【讨论】:

    • @tkxgoogle 如果这回答了您的问题,请勾选接受答案。谢谢。
    【解决方案2】:

    您也可以sort_index提供密钥:

    df.sort_index(axis=1, key=lambda s: s.str[4:])
    
        new_col     old_col     new_elements    old_elements    new_val     old_val
    0   0   2   384444683   423483819   593     480
    1   1   32  384444684   248239340   594     341
    2   2   0   384444686   249289049   596     342
    

    【讨论】:

      【解决方案3】:

      我不是专家,但我会这样做:

      fields = ['new_col', 'old_col', 'new_elements', 'old_elements', 'new_val', 'old_val']
      
      df = df[fields]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-02
        • 1970-01-01
        • 2021-04-01
        • 2015-07-23
        相关资源
        最近更新 更多