EmJ
EmJ

Reputation: 4608

How to order dataframe using a list in pandas

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.

Upvotes: 0

Views: 35

Answers (1)

BENY
BENY

Reputation: 323226

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

Upvotes: 1

Related Questions