1

I have a pandas DataFrame containing probabilities. What I need is a new DataFrame where each row contains the indices of the sorted row. Example:

df = pd.DataFrame([[0.5,0.7,0.1],[0.1,0.7,0.5]])
df
     0    1    2
0  0.5  0.7  0.1
1  0.1  0.7  0.5

new_df = some sort operation on df
new_df
    0  1  2
0   1  0  2
1   2  0  1

I know how to do it the hard way, using multiple loops and such. I found references to sorting values but no "sorting" function that returned the indices. Anyone some suggestion?

4
  • use .index to get the indices for each column after sort (ensure NOT inplace), then build the required dataframe! Commented Jan 6, 2021 at 11:12
  • 1
    how do you have 2,1,0 in the second row? shouldnt it be 1,2,0? Commented Jan 6, 2021 at 11:28
  • 1
    @anky: He just has a typo in his definition of df (the output suggests df[1][1] was 0.5 instead of the 0.7 stated in the example). I'd probably just do df.transform(lambda s: np.argsort(-s.values), axis=1) Commented Jan 6, 2021 at 11:35
  • @Anky, i see what you mean, typo indeed. sorry Commented Jan 6, 2021 at 12:06

1 Answer 1

2

you can use numpy for that with argsort:

df = pd.DataFrame([[0.5,0.7,0.1],[0.1,0.7,0.5]])
array = df.values.argsort(axis=1)[:,::-1]
new_df  = pd.DataFrame(array)

output new_df:

    0   1   2
0   1   0   2
1   1   2   0

Note:

as commented by @anky there is something that doesnt make sense in the ouput you show,, also i assumed you want descending order and thats why the [:,::-1] slice in the result/

UPDATE

as @anky suggested in comments here it is still using the same idea of argsort, this is more strightforward solution then df.values.argsort(axis=1)[:,::-1]:

np.argsort(-df)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.