grokkaine
grokkaine

Reputation: 821

pandas rearrange dataframe to have all values in ascending order per every column independently

The title should say it all, I want to turn this DataFrame:

A NaN 4 3
B 2 1 4
C 3 4 2
D 4 2 8

into this DataFrame:

A 2 1 2
B 3 2 3
C 4 4 4
D NaN 4 8

And I want to do it in a nice manner. The ugly solution would be to take every column and form a new DataFrame. To test, use:

d = {'one':[None, 2, 3, 4],
     'two':[4, 1, 4, 2],
     'three':[3, 4, 6, 8],}
df = pd.DataFrame(d, index = list('ABCD'))

Upvotes: 3

Views: 1044

Answers (1)

unutbu
unutbu

Reputation: 879291

The desired sort ignores the index values, so the operation appears to be more like a NumPy operation than a Pandas one:

import pandas as pd

d = {'one':[None, 2, 3, 4],
     'two':[4, 1, 4, 2],
     'three':[3, 4, 6, 8],}
df = pd.DataFrame(d, index = list('ABCD'))

#    one  three  two
# A  NaN      3    4
# B    2      4    1
# C    3      6    4
# D    4      8    2

arr = df.values
arr.sort(axis=0)
df = pd.DataFrame(arr, index=df.index, columns=df.columns)

print(df)

yields

   one  three  two
A    2      3    1
B    3      4    2
C    4      6    4
D  NaN      8    4

Upvotes: 4

Related Questions