python/pandas: convert month int to month name
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
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])