logo_learn_stats

Pandas: Learn how to Calculate Timedelta in Months

Posted on
banner 336x280

You’ll virtue please see serve as to calculate a timedelta in months between two columns of a pandas DataFrame:

def month_diff(x, y):
    stop = x.dt.to_period('M').view(dtype="int64")
    arrive = y.dt.to_period('M').view(dtype="int64")
    go back end-start

Please see instance displays how one can virtue this serve as in follow.

banner 468x60

Instance: Calculate Timedelta in Months in Pandas

Assume we have now please see pandas DataFrame:

import pandas as pd

#assemble DataFrame
df = pd.DataFrame({'tournament': ['A', 'B', 'C'],
                   'start_date': ['20210101', '20210201', '20210401'],
                   'end_date': ['20210608', '20210209', '20210801'] })

#convert arrive year and stop year columns to datetime
df['start_date'] = pd.to_datetime(df['start_date'])
df['end_date'] = pd.to_datetime(df['end_date'])

#view DataFrame
print(df)

  tournament start_date   end_date
0     A 2021-01-01 2021-06-08
1     B 2021-02-01 2021-02-09
2     C 2021-04-01 2021-08-01

Now assume we’d love to calculate the timedelta (in months) between the start_date and end_date columns.

To take action, we’ll first outline please see serve as:

#outline serve as to calculate timedelta in months between two columns
def month_diff(x, y):
    stop = x.dt.to_period('M').view(dtype="int64")
    arrive = y.dt.to_period('M').view(dtype="int64")
    go back end-start

Nearest, we’ll virtue this serve as to calculate the timedelta in months between the start_date and end_date columns:

#calculate age residue between arrive year and stop year columns
df['month_difference'] = month_diff(df.end_date, df.start_date)

#view up to date DataFrame
df

    tournament	start_date	  end_date	month_difference
0	A	2021-01-01	2021-06-08	5
1	B	2021-02-01	2021-02-09	0
2	C	2021-04-01	2021-08-01	4

The month_difference column presentations the timedelta (in months) between the start_date and end_date columns.

Extra Assets

Please see tutorials provide an explanation for how one can carry out alternative usual operations in pandas:

Learn how to Convert Columns to DateTime in Pandas
Learn how to Convert Datetime to While in Pandas
Learn how to Draw out Era from While in Pandas

banner 336x280

Leave a Reply

Your email address will not be published. Required fields are marked *