使用 Pandas 对 TimeDelta 对象进行加法和减法 - Python
TimeDelta模块用于表示 pandas 模块中的时间,可以有多种使用方式。执行加法和减法等操作对于每种语言都非常重要,但在日期和时间上执行这些任务可能非常有价值。
TimeDelta 数据帧或系列上的操作 –
1) 加法 –
df['Result'] = df['TimeDelta1'] + df['TimeDelta2']
2) 减法——
df['Result'] = df['TimeDelta1'] - df['TimeDelta2']
返回:执行操作后返回数据帧。
示例 #1:
在这个例子中,我们可以看到,通过对 date 和 time 使用各种操作,我们能够在具有 TimeDelta 对象值的数据帧上获得加法和减法。
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)
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)
输出 :
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
示例 #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)
输出 :
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