Convert pandas datetime month to string representation

Viewed 18081

I want to have a pandas DataFrame with a timestamp column and want to create a column with just the month. I want to have the month column with string representations of the month, not with integers. I have done something like this:

df['Dates'] = pd.to_datetime(df['Dates'])
df['Month'] = df.Dates.dt.month
df['Month'] = df.Month.apply(lambda x: datetime.strptime(str(x), '%m').strftime('%b'))

However, this is some kind of a brute force approach and not very performant. Is there a more elegant way to convert the integer representation of the month into a string representation?

2 Answers

For versions pandas 0.23.0+ is possible use dt.month_name:

df['month'] = df['dates'].dt.month_name()
print (df)

        dates      month
0  2016-01-31    January
1  2016-02-29   February
2  2016-03-31      March
3  2016-04-30      April
4  2016-05-31        May
5  2016-06-30       June
6  2016-07-31       July
7  2016-08-31     August
8  2016-09-30  September
9  2016-10-31    October
10 2016-11-30   November
11 2016-12-31   December
12 2017-01-31    January
Related