我有一个数据帧,它以分和秒的形式表示时间,格式为mm:ss.ms或00:00.00。我需要使用dtype float将整列值转换为秒。dataframe列如下所示:
resultsorig['fastestLapTime']
Out[41]:
0 01:27.5
1 01:27.7
2 01:28.1
3 01:28.6
4 01:27.4
24735 01:21.8
24736 01:22.5
24737 01:22.0
24738 01:20.4
24739 01:24.0
Name: fastestLapTime, Length: 24740, dtype: object
我发现的一切都不起作用
更新:我过去曾尝试过以下方法,但效果不错,但不适用于此数据帧,我不确定原因:
resultsorig=resultsorig[~resultsorig['fastestLapTime'].str.contains(":")]
resultsorig['fastestLapTime']=pd.to_numeric([resultsorig['fastestLapTime'])
试试这个
您可以使用pandas
to_timedelta()
函数将这些字符串转换为timedelta值。timedelta值有一个total_seconds()
方法,它将为您提供所需的结果。在pandas中,您可以通过dt
访问器访问total_seconds()
方法导致
"00:" + resultsorig['fastestLapTime']
是必需的,因为to_timedelta()
需要“HH:MM:SS.m”格式的时间,所以这会将小时部分添加到字符串的开头你没有提供预期的输出,所以我猜了一下
df['fastestLapTime'].map(lambda x: sum(x * float(t) for x, t in zip([60.0, 1.0], x.split(':')))
相关问题 更多 >
编程相关推荐