Wednesday, July 3, 2024
HomeLanguagesPythonAddition and Subtraction on TimeDelta objects using Pandas – Python

Addition and Subtraction on TimeDelta objects using Pandas – Python

TimeDelta module is used to represent the time in the pandas module and can be used in various ways. Performing operations like addition and subtraction are very important for every language but performing these tasks on dates and time can be very valuable. 

Operations on TimeDelta dataframe or series – 

1) Addition – 

df['Result'] = df['TimeDelta1'] + df['TimeDelta2']

2) Subtraction – 

df['Result'] = df['TimeDelta1'] - df['TimeDelta2']

Return: Return the dataframe after operations is performed.

Example #1 :

In this example, we can see that by using various operations on date and time, we are able to get the addition and subtraction on the dataframe having TimeDelta object values.

Python3




# import pandas and numpy
import pandas as pd
import numpy as np
  
# Perform addition operation
a = pd.Series(pd.date_range('2020-8-10', periods=5, freq='D'))
b = pd.Series([pd.Timedelta(days=i) for i in range(5)])
  
gfg = pd.DataFrame({'A': a, 'B': b})
gfg['Result'] = gfg['A'] + gfg['B']
  
print(gfg)


Output :

            A             B        Result

0 2020-08-10 0 days 2020-08-10

1 2020-08-11 1 days 2020-08-12

2 2020-08-12 2 days 2020-08-14

3 2020-08-13 3 days 2020-08-16

4 2020-08-14 4 days 2020-08-18

Example #2 :

Python3




# import pandas and numpy
import pandas as pd
import numpy as np
  
# Perform addition operation
a = pd.Series(pd.date_range('2020-8-10', periods=4, freq='D'))
b = pd.Series([pd.Timedelta(days=i) for i in range(4)])
  
gfg = pd.DataFrame({'A': a, 'B': b})
gfg['Result'] = gfg['A'] - gfg['B']
  
print(gfg)


Output :

           A             B        Result

0 2020-08-10 0 days 2020-08-10

1 2020-08-11 1 days 2020-08-10

2 2020-08-12 2 days 2020-08-10

3 2020-08-13 3 days 2020-08-10

Calisto Chipfumbu
Calisto Chipfumbuhttp://cchipfumbu@gmail.com
I have 5 years' worth of experience in the IT industry, primarily focused on Linux and Database administration. In those years, apart from learning significant technical knowledge, I also became comfortable working in a professional team and adapting to my environment, as I switched through 3 roles in that time.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments