0

I have a pandas dataframe as follows.

import pandas as pd
data = [['Alex',10, 175],['Bob',12, 178],['Clarke',13, 179]]
df = pd.DataFrame(data,columns=['Name','Age', 'Height'])
print(df)

I also have a list as follows.

mynames = ['Emj', 'Bob', 'Jenne', 'Alex', 'Clarke']

I want to order the rows of my dataframe in the order of mynames list. In other words, my output should be as follows.

   Name  Age  Height
0   Bob   12     178
1   Alex   10     175  
2  Clarke   13     179

I was trying to do this as follows. I am wondering if there is an easy way to do this in pandas than converting the dataframe to list.

I am happy to provide more details if needed.

1

1 Answer 1

1

You can do pd.Categorical + argsort

df=df.loc[pd.Categorical(df.Name,mynames).argsort()]
     Name  Age  Height
1     Bob   12     178
0    Alex   10     175
2  Clarke   13     179
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.