Search code examples
pythonpandaslistdataframereorderlist

How to reorder a dataframe based on a list? pandas


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!


Solution

  • 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