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.

EmJ
  • 4,398
  • 9
  • 44
  • 105

1 Answers1

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
BENY
  • 317,841
  • 20
  • 164
  • 234