Custom sorting in pandas dataframe

前端 未结 4 2155
情歌与酒
情歌与酒 2020-11-22 16:34

I have python pandas dataframe, in which a column contains month name.

How can I do a custom sort using a dictionary, for example:

custom_dict = {\'         


        
4条回答
  •  孤街浪徒
    2020-11-22 17:10

    import pandas as pd
    custom_dict = {'March':0,'April':1,'Dec':3}
    
    df = pd.DataFrame(...) # with columns April, March, Dec (probably alphabetically)
    
    df = pd.DataFrame(df, columns=sorted(custom_dict, key=custom_dict.get))
    

    returns a DataFrame with columns March, April, Dec

提交回复
热议问题