问题描述
我有一个数据框,想对所有列进行降序或升序排序.
I have a dataframe and want to sort all columns independently in descending or ascending order.
import pandas as pd
data = {'a': [5, 2, 3, 6],
'b': [7, 9, 1, 4],
'c': [1, 5, 4, 2]}
df = pd.DataFrame.from_dict(data)
a b c
0 5 7 1
1 2 9 5
2 3 1 4
3 6 4 2
当我使用 sort_values() >为此,它(对我而言)无法正常工作,只能对一列进行排序:
When I use sort_values() for this it does not work as expected (to me) and only sorts one column:
foo = df.sort_values(by=['a', 'b', 'c'], ascending=[False, False, False])
a b c
3 6 4 2
0 5 7 1
2 3 1 4
1 2 9 5
如果我使用此中的解决方案,则可以获得预期的结果应用lambda函数的答案:
I can get the desired result if I use the solution from this answer which applies a lambda function:
bar = df.apply(lambda x: x.sort_values().values)
print(bar)
a b c
0 2 1 1
1 3 4 2
2 5 7 4
3 6 9 5
但这对我来说似乎有点笨拙.
But this looks a bit heavy-handed to me.
sort_values()上面的示例,如何在没有lambda函数的情况下以熊猫的方式对数据框中的所有列进行排序?
What's actually happening in the sort_values() example above and how can I sort all columns in my dataframe in a pandas-way without the lambda function?
推荐答案
您可以使用 numpy.sort
和DataFrame
构造函数:
You can use numpy.sort
with DataFrame
constructor:
df1 = pd.DataFrame(np.sort(df.values, axis=0), index=df.index, columns=df.columns)
print (df1)
a b c
0 2 1 1
1 3 4 2
2 5 7 4
3 6 9 5
以降序排列:
arr = df.values
arr.sort(axis=0)
arr = arr[::-1]
print (arr)
[[6 9 5]
[5 7 4]
[3 4 2]
[2 1 1]]
df1 = pd.DataFrame(arr, index=df.index, columns=df.columns)
print (df1)
a b c
0 6 9 5
1 5 7 4
2 3 4 2
3 2 1 1
这篇关于使用sort_values()独立对 pandas DataFrame的所有列进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!