代码之家  ›  专栏  ›  技术社区  ›  Lucas Aimaretto

根据排序输出重新排列数据帧中的列

  •  1
  • Lucas Aimaretto  · 技术社区  · 1 年前

    我有以下数据帧:

    df = pd.DataFrame(
        {
            'a':[1,2,3,4,5,6],
            'b':[1,1,3,3,5,5],
            'c':[1,2,3,4,5,6],                
            'd':[1,1,1,1,1,5],
        }
    )
    
    In [1051]: df
    Out[1051]: 
       a  b  c  d
    0  1  1  1  1
    1  2  1  2  1
    2  3  3  3  1
    3  4  3  4  1
    4  5  5  5  1
    5  6  5  6  5
    

    如果我使用所有列对df进行排序,我会得到以下结果:

    In [1055]: columns = list(df.columns)
          ...: 
          ...: dfSorted = df.sort_values(by=columns, ascending=False)
          ...: 
          ...: print(dfSorted)
       a  b  c  d
    5  6  5  6  5
    4  5  5  5  1
    3  4  3  4  1
    2  3  3  3  1
    1  2  1  2  1
    0  1  1  1  1
    

    我想重新排列从行之间差异最小的列开始的列的顺序,使最后一列成为差异最大的列。在我的例子中,预期的顺序应该是d,b,c,a。

    这是因为列 d 只有两个不同的值(1和5),而列 c a 具有不同的所有值。柱 b 是中间的情况。。。

    In [1056]: dfSorted[['d','b','c','a']]
    Out[1056]: 
       d  b  c  a
    5  5  5  6  6
    4  1  5  5  5
    3  1  3  4  4
    2  1  3  3  3
    1  1  1  2  2
    0  1  1  1  1
    

    知道吗?谢谢

    2 回复  |  直到 1 年前
        1
  •  2
  •   e-motta    1 年前

    一个可能的解决方案是对列进行排序(使用 sort_values )按数量 nunique 值,并将其用于 reindex :

    df = df.reindex(df.nunique().sort_values().index, axis=1)
    
       d  b  a  c
    5  5  5  6  6
    4  1  5  5  5
    3  1  3  4  4
    2  1  3  3  3
    1  1  1  2  2
    0  1  1  1  1
    
        2
  •  1
  •   user24714692    1 年前

    您可以使用 nunique() :

    import pandas as pd
    
    
    def _nu(df):
        NU = df.nunique().sort_values().index
        DNU = df[NU]
        return DNU.sort_values(by=list(NU), ascending=False)
    
    
    df = pd.DataFrame({
        'a': [1, 2, 3, 4, 5, 6],
        'b': [1, 1, 3, 3, 5, 5],
        'c': [1, 2, 3, 4, 5, 6],
        'd': [1, 1, 1, 1, 1, 5],
    })
    
    print(_nu(df))