Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas sort all rows

Is there a way to sort each row of a pandas data frame?

I don't care about columns names or row indexes, I just want a table with the values of each row sorted from highest to lowest.

like image 453
Mustard Tiger Avatar asked Jan 22 '26 21:01

Mustard Tiger


1 Answers

You can use np.sort with axis=1 on the numpy data:

# sample data
np.random.seed(1)
df = pd.DataFrame(np.random.randint(1,10, (2,4)))

# output
pd.DataFrame(np.sort(df.values, axis=1)[:,::-1], 
             index=df.index, 
             columns=df.columns)

Output:

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

If you want to override your original dataframe:

df[:] = np.sort(df.values, axis=1)[:,::-1]

Update

np.sort(df)[:,::-1] works as well, df is downcast to a numpy array, and axis=-1 is default.

like image 129
Quang Hoang Avatar answered Jan 25 '26 10:01

Quang Hoang