2

Given a dataframe and a list, with the values of a column of a dataframe. (the list is equaly long as the rows of the dataframe and each value appear exactly ones) How can i sort the rows in the dataframe according to the order in the list?

import pandas as pd
df = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice'], 
                   'income': [40000, 50000, 42000]})
z = ["Jane", "Alice", "Bob"]

1 Answer 1

1

Let us do pd.Categorical with argsort

df=df.iloc[pd.Categorical(df.user,z).argsort()]
df
    user  income
1   Jane   50000
2  Alice   42000
0    Bob   40000

Or reindex

df=df.set_index('user').reindex(z).reset_index()
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.