Pandas:将列中所有值的时间转换为秒

2024-10-05 10:06:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧,它以分和秒的形式表示时间,格式为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'])

Tags: 数据namedataframe格式时间floatoutlength
3条回答

试试这个

df['fastestLapTime']=df['fastestLapTime'].apply(lambda x: float(x.split(':')[0])*60+float(x.split(':')[1]))

您可以使用pandasto_timedelta()函数将这些字符串转换为timedelta值。timedelta值有一个total_seconds()方法,它将为您提供所需的结果。在pandas中,您可以通过dt访问器访问total_seconds()方法

import pandas as pd
resultsorig = pd.DataFrame(['01:27.5', '01:27.7', '01:28.1', '01:28.6', '01:27.4'], columns = ['fastestLapTime'])

pd.to_timedelta("00:" + resultsorig['fastestLapTime']).dt.total_seconds()

导致

0    87.5
1    87.7
2    88.1
3    88.6
4    87.4
Name: fastestLapTime, dtype: float64

"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(':')))

0    87.5
1    87.7
2    88.1
3    88.6
4    87.4
5    81.8
6    82.5
7    82.0
8    80.4
9    84.0

相关问题 更多 >

    热门问题