Reputation: 3671
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.
Upvotes: 3
Views: 1144
Reputation: 150785
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]
np.sort(df)[:,::-1]
works as well, df
is downcast to a numpy array, and axis=-1
is default.
Upvotes: 3