Pandas Number of Months Between Two Dates

Given a pandas dataframe, we have to find the number of months between two dates.
Submitted by Pranit Sharma, on October 18, 2022

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

We are given a DataFrame with two columns, both have the date as their values, we need to create an extra column that will have the number of months between the w two dates. We will simply find the difference between the two dates and divide it by np.timedelta method.

Finding the number of months between two dates

The Timedeltas is the method used for representing differences in time, which is expressed in different units, like hours, minutes, and seconds.

The Timedelta method takes a string inside it as a parameter in which we simply define the time in human language and it converts that string to measure time differences.

Let us understand with the help of an example,

Python program to find the number of months between two dates

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a dictionary
d = {
    'd1':['2012-09-10','2011-11-11','2010-10-10'],
    'd2':['2022-11-11','2012-09-23','2011-09-11']
}

# Creating a DataFrame
df = pd.DataFrame(d)

# Display original DataFrame
print("Original Dataframe:\n",df,"\n")

# Converting d1 and d2 to datetime
df['d1'] = pd.to_datetime(df['d1'])
df['d2'] = pd.to_datetime(df['d2'])

# Getting the diff between to dates 
# in form of month
df['month_diff'] = ((df.d2 - df.d1)/np.timedelta64(1, 'M'))

# Display Modified DataFrame
print('Modified DataFrame:\n',df)

Output

The output of the above program is:

Example: Pandas Number of Months Between Two Dates

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.