python/pandas: convert month int to month name
You can do this efficiently with combining calendar.month_abbr
and df[col].apply()
import calendardf['Month'] = df['Month'].apply(lambda x: calendar.month_abbr[x])
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 client0 Feb sss1 Dec yyy2 Jun www
You can do this easily with a column apply.
import pandas as pddf = pd.DataFrame({'client':['sss', 'yyy', 'www'], 'Month': ['02', '12', '06']})look_up = {'01': 'Jan', '02': 'Feb', '03': 'Mar', '04': 'Apr', '05': 'May', '06': 'Jun', '07': 'Jul', '08': 'Aug', '09': 'Sep', '10': 'Oct', '11': 'Nov', '12': 'Dec'}df['Month'] = df['Month'].apply(lambda x: look_up[x])df Month client0 Feb sss1 Dec yyy2 Jun www