📜  使用 Pandas 对 TimeDelta 对象进行加法和减法 - Python

📅  最后修改于: 2022-05-13 01:55:46.426000             🧑  作者: Mango

使用 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)


输出 :

示例 #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)

输出 :