将两个日期时间列相加

3

我有一个包含两列的数据框,例如:

A                B 
00:01:05         2018-10-10 23:58:10

我希望您能得到第三列C,它是A + B的总和。
A                B                             C
00:01:05         2018-10-10 23:58:10           2018-10-10 23:59:15

如果我执行:

df['C']= df['A'] + df['B']

我理解

cannot add DatetimeArray and DatetimeArray

4
将它们先转换为 pd.Timedelta - rafaelc
2个回答

5

通过to_timedelta将列A转换为时间差,如果需要的话,将列B转换为to_datetime

df = pd.DataFrame({'A':['00:01:05'],
                   'B':['2018-10-10 23:58:10']})

df['C'] = pd.to_timedelta(df['A']) + pd.to_datetime(df['B'])
print (df)
          A                    B                   C
0  00:01:05  2018-10-10 23:58:10 2018-10-10 23:59:15

如果列A包含Python时间:
df['C'] = pd.to_timedelta(df['A'].astype(str)) + pd.to_datetime(df['B'])

4
这是您的样本数据框:
sample = pd.DataFrame()

sample['A'] = ['00:01:05']
sample['B'] = ['2018-10-10 23:58:10']

将列 B 转换为 pd.Timstamp,将 A 转换为 pd.Timedelta,如下所示:

sample['B'] = pd.to_datetime(sample['B'])
sample['A'] = pd.to_timedelta(sample['A'], unit='m')

然后正常添加列,

sample['C'] = sample['B'] + sample['A']

    A                    B                     C
0   00:01:05    2018-10-10 23:58:10     2018-10-10 23:59:15

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接