[英]How to convert time in days, hours, minutes, and seconds to only seconds?
我有以下数据框列:
我需要将 csv 列中的对象字符串数据转换为总秒数。
示例:10m -> 600s
我试过这个代码:
df.duration = str(datetime.timedelta(df['duration']))
但是显示以下错误
类型错误:timedelta 天组件不支持的类型:系列
'duration'
转换为秒的正确矢量化方法是:
'duration'
转换为'duration'
增量pd.Timedelta(seconds=1)
.dt.seconds
timedelta
以及为什么.total_seconds
方法完全是意外。import pandas as pd
# test data
df = pd.DataFrame({'duration': ['10d 15h 23m', '10d 18h 13m']})
# convert duration to a timedelta
df.duration = pd.to_timedelta(df.duration)
# calculate total_seconds
df['total_sec'] = df.duration / pd.Timedelta(seconds=1)
# get seconds for just hours, minutes, seconds
df['sec_without_days'] = df.duration.dt.seconds
# display(df)
duration total_sec sec_without_days
0 10 days 15:23:00 919380.0 55380
1 10 days 18:13:00 929580.0 65580
您可以使用pandas.to_timedelta()
将字符串转换为 timedelta 对象,然后应用 lambda 函数来获取持续时间的总秒数:
import pandas as pd
df['duration'] = pd.to_timedelta(df['duration']).apply(lambda x: x.total_seconds())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.