gpt4 book ai didi

python - 在 Pandas 数据框中将两个时间列添加在一起?

转载 作者:行者123 更新时间:2023-12-01 00:41:54 25 4
gpt4 key购买 nike

我有以下数据:

 time_begin  DRTN_IN_SCND
16:22:16 439
16:29:37 53
16:30:33 85

我想创建一个新列,添加 time_begin 和 DRTN_IN_SCND(以秒为单位的持续时间)以创建新时间。

我试过了:
df['new_time'] = df['time_begin'].apply(lambda x: (dt.datetime.combine(dt.datetime(1,1,1), x,) + dt.timedelta(seconds=df.DRTN_IN_SCND)).time())

这在 dt.timedelta(seconds=3) 时有效,但当我更改为 dt.timedelta(seconds=df.DRTN_IN_SCND) 时无效。我收到以下错误。
TypeError: unsupported type for timedelta seconds component: Series

有谁知道如何解决这个问题或以另一种方式来完成我想要做的事情?谢谢!

最佳答案

您必须转换 DRTN_IN_SCNDtime_begin如果您想对列进行正确计算,可以对增量进行计时,pandas 有 to_timedelta这非常方便:

df['DRTN_IN_SCND'] = pd.to_timedelta(df['DRTN_IN_SCND'], unit='s')
df['time_begin'] = pd.to_timedelta(df['time_begin'])
df['new_time'] = df['time_begin'] + df['DRTN_IN_SCND']

这将为您提供新列 new_time :
   time_begin  DRTN_IN_SCND  new_time
0 16:22:16 00:07:19 16:29:35
1 16:29:37 00:00:53 16:30:30
2 16:30:33 00:01:25 16:31:58

关于python - 在 Pandas 数据框中将两个时间列添加在一起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37076455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com