Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python/pandas: convert month int to month name

Most of the info I found was not in python>pandas>dataframe hence the question.

I want to transform an integer between 1 and 12 into an abbrieviated month name.

I have a df which looks like:

   client Month 1  sss    02 2  yyy    12 3  www    06 

I want the df to look like this:

   client Month 1  sss    Feb 2  yyy    Dec 3  www    Jun 
like image 588
Boosted_d16 Avatar asked Jun 04 '16 00:06

Boosted_d16


People also ask

How do I get the month name from a number in Python?

To get the month name from a number in Python, the easiest way is with strftime() and passing “%M”. You can also use the calendar module and the month_name() function.

How do you get the current month in a string in Python?

Method #1 : Using strftime() + %B In this, we use strftime() which converts date object to a string using a format, and by providing %B, it's enforced to just return a Month Name.


2 Answers

You can do this efficiently with combining calendar.month_abbr and df[col].apply()

import calendar df['Month'] = df['Month'].apply(lambda x: calendar.month_abbr[x]) 
like image 149
EoinS Avatar answered Sep 19 '22 23:09

EoinS


Since the abbreviated month names is the first three letters of their full names, we could first convert the Month column to datetime and then use dt.month_name() to get the full month name and finally use str.slice() method to get the first three letters, all using pandas and only in one line of code:

df['Month'] = pd.to_datetime(df['Month'], format='%m').dt.month_name().str.slice(stop=3)  df    Month client 0   Feb sss 1   Dec yyy 2   Jun www 
like image 40
today Avatar answered Sep 22 '22 23:09

today