Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort all columns of a dataframe

I have a dataframe of 2000 rows and 500 columns. I want to sort every column in ascending order. The columns don't have names they're just numbered 0-500.

Random data: df = pandas.DataFrame(np.random.randint(0,100,size=(2000, 500)), columns=range(500))

Using df.sort_values(by=0,axis=0) sorts the 0th column, as expected. But then using df.sort_values(by=1,axis=0) sorts the 1st column but shuffles the 0th column again. In other words, I want

index  0  1  2
1      5  5  5
2      6  7  5
3      7  9  8

But I can only ever get one column sorted at a time. I've tried df.sort_values(by=df.columns[0:524],axis=0) but that throws a key error.

like image 340
OfOurOwn Avatar asked Jan 06 '17 13:01

OfOurOwn


1 Answers

I think the most elegant solution nowadays is df.transform(np.sort).

like image 189
TheBamf Avatar answered Oct 05 '22 10:10

TheBamf