2

I have a df and I want to reorder it based on athe list as shown using Python:

df=pd.DataFrame({'Country':["AU","DE","UR","US","GB","SG","KR","JP","CN"],'Stage #': [3,2,6,6,3,2,5,1,1],'Amount':[4530,7668,5975,3568,2349,6776,3046,1111,4852]})

df

list=["US","CN","GB","AU","JP","KR","UR","DE","SG"]

How can I do that? Any thoughts? Thanks!

Boomshakalaka
  • 521
  • 1
  • 6
  • 19

1 Answers1

6

Use pd.Categorical

list_ = ["US","CN","GB","AU","JP","KR","UR","DE","SG"]

df['Country'] = pd.Categorical(df.Country, categories = list_, ordered = True)
df.sort_values(by='Country')

Also, do not name your variable list because that would override the built-in list command

rafaelc
  • 57,686
  • 15
  • 58
  • 82