Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

python - Sort all columns of a pandas DataFrame independently using sort_values()

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

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

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

EDIT:

Answer with descending order:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...