在 pandas 数据框中将两个时间列加在一起?

编程入门 行业动态 更新时间:2024-10-28 14:36:49
本文介绍了在 pandas 数据框中将两个时间列加在一起?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下数据:

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

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

I would like to make a new column that adds time_begin and DRTN_IN_SCND (the duration in seconds) to create a new time.

我尝试过:

df['new_time'] = df['time_begin'].apply(lambda x: (dt.datetimebine(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)时不起作用.我收到以下错误.

This works if dt.timedelta(seconds=3) but does not work when I change to dt.timedelta(seconds=df.DRTN_IN_SCND). I get the following error.

TypeError: unsupported type for timedelta seconds component: Series

有人知道如何解决此问题或以其他方式完成我要尝试的工作吗?谢谢!

Does anyone know how to fix this or of another way to accomplish what I'm trying to do? Thanks!

推荐答案

如果要对列进行正确的计算,则必须将DRTN_IN_SCND和time_begin转换为时间增量,pandas具有 to_timedelta 十分方便:

You'll have to convert the DRTN_IN_SCND and time_begin to time deltas if you want to do properly calculations on the columns, pandas has to_timedelta which is pretty handy:

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

更多推荐

在 pandas 数据框中将两个时间列加在一起?

本文发布于:2023-10-19 20:38:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1508704.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:框中   加在   两个   时间   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!