Home »
Python »
Python Programs
Pandas convert month int to month name
Given a pandas dataframe, we have to convert month int to month name.
By Pranit Sharma Last updated : October 03, 2023
Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.
Problem statement
Suppose, we are given a DataFrame with a column named Month but it contains the month number and we want to convert this month number to month name. For example, if the value is 2, we need to convert this 2 into February.
Converting month int to month name
For this purpose, we will first import calendar library which contains all the methods related to date, month, and years.
Calendar library support a method called month.abbr() which allows us to convert the integer values into the respective month name. This integer values is passed inside this method as a parameter.
Let us understand with the help of an example,
Python program to convert month int to month name
# Importing pandas package
import pandas as pd
# Importing calendar
import calendar
# Creating a Dictionary
d = {
'Date':[12,16,22,28,6],
'Month':[2,6,12,7,3]
}
# Creating a DataFrame
df = pd.DataFrame(d)
# Display original DataFrame
print("Original DataFrame:\n",df,"\n")
# getting month name
df['Month'] = df['Month'].apply(lambda x: calendar.month_abbr[x])
# Display modified DataFrame
print("Modified DataFrame:\n",df)
Output
The output of the above program is:
Python Pandas Programs »