Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (17.6k points)

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 = {'March':0, 'April':1, 'Dec':3}  

1 Answer

0 votes
by (41.4k points)
edited by

Making the month column a categorical one and specifying the ordering:

df['m'] = pd.Categorical(df['m'], ["March", "April", "Dec"])

df  # looks the same!

Output:

   a  b     m

0  1 2  March

1  5 6    Dec

2  3 4  April

Now, when you sort the month column it will sort with respect to that list:

df.sort("m")

Output:

   a  b     m

0  1 2  March

2  3 4  April

1  5 6    Dec

Note: if a value is not in the list it will be converted to NaN.

If you want to learn Python proogramming language for Data Science then you can watch this complete video tutorial:

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 31, 2019 in Data Science by sourav (17.6k points)
0 votes
1 answer

Browse Categories

...