Pandas - 按任意列中最高值排序数据框

3

我有这样格式化的数据

df = pd.DataFrame(data=[['Steve', '3', '2'],
                        ['Smith', '4', '3'],
                        ['Scott', '0', '5'],
                        ['Simon', '1', '8']],
                  columns=['Name', 'Count1', 'Count2'])

使用df.sort_values(by=['Count1','Count2'], ascending=[False,False], inplace=True)进行排序,将会得到以下结果

    Name Count1 Count2
1  Smith      4      3
0  Steve      3      2
3  Simon      1      8
2  Scott      0      5

我希望将任意列中最高个体值的行放在顶部。 这是我期望的输出结果:
    Name Count1 Count2
3  Simon      1      8
2  Scott      0      5
1  Smith      4      3
0  Steve      3      2

如何适当地处理这个问题?

3个回答

5

IIUC argsort

df = df.iloc[(-df.drop('Name',1).max(axis=1)).argsort()]
    Name Count1 Count2
3  Simon      1      8
2  Scott      0      5
1  Smith      4      3
0  Steve      3      2

1
计算每列的最大值,然后按照索引排序并进行参考。
df.iloc[df.iloc[:, 1:].max(axis=1).sort_values(ascending=False).index]

    Name Count1 Count2
3  Simon      1      8
2  Scott      0      5
1  Smith      4      3
0  Steve      3      2

1
你可以这样做:

result = df.assign(order=df.iloc[:, 1:].max(axis=1)).sort_values('order', ascending=False).drop('order', axis=1)
print(result)

输出

    Name Count1 Count2
3  Simon      1      8
2  Scott      0      5
1  Smith      4      3
0  Steve      3      2

作为替代方案:
order = df.drop('Name', axis=1).max(1).sort_values(ascending=False).index
result = df.iloc[order]
print(result)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接