Pandas Timedelta in Months

Learn, how can we show months inside timedelta in pandas DataFrame? 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.

Showing months inside timedelta in pandas DataFrame

Basically, we need to calculate the elapsed months in pandas DataFrame, for this purpose, we will calculate the monthly difference between the date value of one column and the date value of another column.

Timedelta 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 show months inside timedelta

# Importing pandas package
import pandas as pd

# Creating a DataFrame
df = pd.DataFrame([pd.Timestamp('20220109'),pd.Timestamp('20220111') ], columns=['date'])

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

# adding column
df['today'] = pd.Timestamp('20220110')

# Display modified DataFrame
print("DataFrame:\n",df,"\n")

# Elapsed months
res = 12 * (df.today.dt.year - df.date.dt.year) + (df.today.dt.month - df.date.dt.month)

# Display result
print("Result:\n",res)

Output

The output of the above program is:

Example: Pandas Timedelta in Months

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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