Home > Software design >  Python sort data frame based on argsort result
Python sort data frame based on argsort result

Time:12-22

I have a pandas data frame df, where I would like to sort the values in each row based on the indices I get from the argsort function. I get the indices as follows:

idx = np.argsort(df, axis=1)

Now I would like to use the result idx to sort all rows of df, as well as all rows of a different data frame (let's call it df2) with the same shape. I am however unable to achieve this. My attempt to sort it using df[idx] didn't work. Any help is greatly appreciated.

CodePudding user response:

Does df.iloc[idx] or df.loc[idx] do the trick?

CodePudding user response:

I managed to achieve what I want. It's probably not the cleanest solution but it does the trick:

idx = np.argsort(df, axis=1)
df_sorted = pd.DataFrame(data=np.take_along_axis(df.to_numpy(), idx.to_numpy(), axis=1), columns=df.columns)
  • Related