我有以下数据框列:
我需要将csv列中的对象字符串数据转换为总秒数。
例如:10m-> 600s
我尝试了以下代码:
df.duration = str(datetime.timedelta(df['duration']))
但是显示以下错误
TypeError:timedelta天组件不受支持的类型:系列
答案 0 :(得分:2)
'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
答案 1 :(得分:1)
您可以使用pandas.to_timedelta()
将字符串转换为timedelta对象,然后应用lambda函数获取持续时间的总秒数:
import pandas as pd
df['duration'] = pd.to_timedelta(df['duration']).apply(lambda x: x.total_seconds())