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
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.
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.
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])
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With