When working with date-related data in Pandas, you often encounter month information represented as numbers (1 for January, 2 for February, etc.). For reporting or display purposes, you might need to convert these month numbers into their full names (e.g., "January") or abbreviations (e.g., "Jan"). Conversely, you might need to convert month names back to numbers for calculations or consistency.
This guide explains how to perform these conversions in a Pandas DataFrame column using Pandas' datetime capabilities and Python's built-in calendar module.
The Goal: Translating Between Month Numbers and Names
We want to transform a column containing:
- Month numbers (integers 1-12) into their corresponding full month names (e.g., 1 -> "January") or abbreviations (e.g., 1 -> "Jan").
- Month names or abbreviations into their corresponding month numbers (e.g., "January" -> 1, "Jan" -> 1).
Example DataFrame
import pandas as pd
data = {
'EmployeeID': ['E01', 'E02', 'E03', 'E04', 'E05'],
'StartMonthNum': [1, 4, 7, 10, 12], # Month numbers
'LeaveMonthName': ['March', 'June', 'September', 'December', 'February'], # Full names
'EventMonthAbbr': ['Jan', 'May', 'Aug', 'Nov', 'Apr'] # Abbreviations
}
df = pd.DataFrame(data)
print("Original DataFrame:")
print(df)Output:
Original DataFrame:
EmployeeID StartMonthNum LeaveMonthName EventMonthAbbr
0 E01 1 March Jan
1 E02 4 June May
2 E03 7 September Aug
3 E04 10 December Nov
4 E05 12 February AprConvert Month Number to Full Month Name
Using pd.to_datetime() and Series.dt.month_name() (Recommended Pandas Way)
This method leverages Pandas' powerful datetime capabilities.
- Convert the month number column to a temporary datetime series.
format='%m'tellsto_datetimeto interpret the numbers as months. Pandas will assign a default year and day (e.g., 1900-01-01 if only month is given this way with%m, or current year/day for some inputs). - Use the
.dt.month_name()accessor on this datetime series.
import pandas as pd
data = {
'EmployeeID': ['E01', 'E02', 'E03', 'E04', 'E05'],
'StartMonthNum': [1, 4, 7, 10, 12], # Month numbers
'LeaveMonthName': ['March', 'June', 'September', 'December', 'February'], # Full names
'EventMonthAbbr': ['Jan', 'May', 'Aug', 'Nov', 'Apr'] # Abbreviations
}
df = pd.DataFrame(data)
df_month_to_name = df.copy()
df_month_to_name['StartMonth_FullName'] = pd.to_datetime(
df_month_to_name['StartMonthNum'], format='%m'
).dt.month_name()
print("DataFrame with full month names (using pd.to_datetime):")
print(df_month_to_name[['StartMonthNum', 'StartMonth_FullName']])Output:
DataFrame with full month names (using pd.to_datetime):
StartMonthNum StartMonth_FullName
0 1 January
1 4 April
2 7 July
3 10 October
4 12 Decemberformat='%m': Crucial for interpreting the integer column as month numbers..dt.month_name(): Returns a Series of full month names.
Using Series.apply() with calendar.month_name
Python's built-in calendar module has an array calendar.month_name where index 1 is 'January', 2 is 'February', etc. (index 0 is an empty string).
import pandas as pd
data = {
'EmployeeID': ['E01', 'E02', 'E03', 'E04', 'E05'],
'StartMonthNum': [1, 4, 7, 10, 12], # Month numbers
'LeaveMonthName': ['March', 'June', 'September', 'December', 'February'], # Full names
'EventMonthAbbr': ['Jan', 'May', 'Aug', 'Nov', 'Apr'] # Abbreviations
}
df = pd.DataFrame(data)
df_month_to_name_cal = df.copy()
df_month_to_name_cal['StartMonth_FullName_Cal'] = df_month_to_name_cal['StartMonthNum'].apply(
lambda month_num: calendar.month_name[month_num]
)
print("DataFrame with full month names (using calendar.month_name):")
print(df_month_to_name_cal[['StartMonthNum', 'StartMonth_FullName_Cal']])Output:
DataFrame with full month names (using calendar.month_name):
StartMonthNum StartMonth_FullName_Cal
0 1 January
1 4 April
2 7 July
3 10 October
4 12 DecemberConvert Month Number to Month Abbreviation (e.g., "Jan")
Using dt.month_name().str.slice(stop=3) or str[:3]
After getting the full month name (as in Method 3.1), you can slice the string to get the first 3 characters.
import pandas as pd
data = {
'EmployeeID': ['E01', 'E02', 'E03', 'E04', 'E05'],
'StartMonthNum': [1, 4, 7, 10, 12], # Month numbers
'LeaveMonthName': ['March', 'June', 'September', 'December', 'February'], # Full names
'EventMonthAbbr': ['Jan', 'May', 'Aug', 'Nov', 'Apr'] # Abbreviations
}
df = pd.DataFrame(data)
df_month_to_abbr = df.copy()
month_names_full = pd.to_datetime(df_month_to_abbr['StartMonthNum'], format='%m').dt.month_name()
df_month_to_abbr['StartMonth_Abbr'] = month_names_full.str.slice(stop=3)
print("DataFrame with month abbreviations (using .dt.month_name().str.slice()):")
print(df_month_to_abbr[['StartMonthNum', 'StartMonth_Abbr']])Output:
DataFrame with month abbreviations (using .dt.month_name().str.slice()):
StartMonthNum StartMonth_Abbr
0 1 Jan
1 4 Apr
2 7 Jul
3 10 Oct
4 12 DecUsing Series.apply() with calendar.month_abbr
The calendar module also has calendar.month_abbr for abbreviations.
import pandas as pd
import calendar # For calendar module examples
data = {
'EmployeeID': ['E01', 'E02', 'E03', 'E04', 'E05'],
'StartMonthNum': [1, 4, 7, 10, 12], # Month numbers
'LeaveMonthName': ['March', 'June', 'September', 'December', 'February'], # Full names
'EventMonthAbbr': ['Jan', 'May', 'Aug', 'Nov', 'Apr'] # Abbreviations
}
df = pd.DataFrame(data)
df_month_to_abbr_cal = df.copy()
df_month_to_abbr_cal['StartMonth_Abbr_Cal'] = df_month_to_abbr_cal['StartMonthNum'].apply(
lambda month_num: calendar.month_abbr[month_num]
)
print("DataFrame with month abbreviations (using calendar.month_abbr):")
print(df_month_to_abbr_cal[['StartMonthNum', 'StartMonth_Abbr_Cal']])Output:
DataFrame with month abbreviations (using calendar.month_abbr):
StartMonthNum StartMonth_Abbr_Cal
0 1 Jan
1 4 Apr
2 7 Jul
3 10 Oct
4 12 DecConvert Month Name (or Abbreviation) to Month Number
To go from month name/abbreviation back to an integer (1-12).
Creating a Mapping Dictionary from calendar
First, create a lookup dictionary mapping month names/abbreviations to their numbers.
import pandas as pd
import calendar
month_name_to_num_dict = {name: num for num, name in enumerate(calendar.month_name) if name}
print(f"Full name to number map: {month_name_to_num_dict}\n")
month_abbr_to_num_dict = {abbr: num for num, abbr in enumerate(calendar.month_abbr) if abbr}
print(f"Abbreviation to number map: {month_abbr_to_num_dict}")Output:
Full name to number map: {'January': 1, 'February': 2, 'March': 3, 'April': 4, 'May': 5, 'June': 6, 'July': 7, 'August': 8, 'September': 9, 'October': 10, 'November': 11, 'December': 12}
Abbreviation to number map: {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6, 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}enumerate(calendar.month_name)gives(0, ''), (1, 'January'), .... We filterif nameorif abbrto skip the empty string at index 0.
Using Series.map() with the Mapping Dictionary
Use the Series.map() method to apply the mapping.
import pandas as pd
import calendar # For calendar module examples
data = {
'EmployeeID': ['E01', 'E02', 'E03', 'E04', 'E05'],
'StartMonthNum': [1, 4, 7, 10, 12], # Month numbers
'LeaveMonthName': ['March', 'June', 'September', 'December', 'February'], # Full names
'EventMonthAbbr': ['Jan', 'May', 'Aug', 'Nov', 'Apr'] # Abbreviations
}
df = pd.DataFrame(data)
df_name_to_num = df.copy()
month_name_to_num_dict = {name: num for num, name in enumerate(calendar.month_name) if name}
month_abbr_to_num_dict = {abbr: num for num, abbr in enumerate(calendar.month_abbr) if abbr}
df_name_to_num['LeaveMonth_Num'] = df_name_to_num['LeaveMonthName'].map(month_name_to_num_dict)
df_name_to_num['EventMonth_Num'] = df_name_to_num['EventMonthAbbr'].map(month_abbr_to_num_dict)
print("DataFrame with month names/abbreviations converted to numbers:")
print(df_name_to_num[['LeaveMonthName', 'LeaveMonth_Num', 'EventMonthAbbr', 'EventMonth_Num']])Output:
DataFrame with month names/abbreviations converted to numbers:
LeaveMonthName LeaveMonth_Num EventMonthAbbr EventMonth_Num
0 March 3 Jan 1
1 June 6 May 5
2 September 9 Aug 8
3 December 12 Nov 11
4 February 2 Apr 4If a month name/abbreviation in your Series is not found in the dictionary, map() will produce NaN for that entry.
Conclusion
Pandas, along with Python's calendar module, provides robust ways to convert between month numbers and their names or abbreviations:
- Month Number to Full Name:
pd.to_datetime(series, format='%m').dt.month_name()(Pandas-idiomatic).series.apply(lambda x: calendar.month_name[x]).
- Month Number to Abbreviation:
pd.to_datetime(series, format='%m').dt.month_name().str[:3].series.apply(lambda x: calendar.month_abbr[x]).
- Month Name/Abbreviation to Number:
- Create a mapping dictionary from
calendar.month_nameorcalendar.month_abbr. - Use
series.map(your_mapping_dict).
- Create a mapping dictionary from
Choose the method that best fits your data and readability preferences. The pd.to_datetime().dt.month_name() approach is often preferred for its directness within the Pandas ecosystem when starting from numbers. For converting names to numbers, the map() method with a pre-built dictionary is very efficient.