Pandas 将列转换为时间

2023-12-22

这是我的 DF

             Start-Time Running-Time Speed-Avg HR-Avg
0    2016-12-18 10:8:14       0:24:2        20    138
1    2016-12-18 10:8:14       0:24:2        20    138
2    2016-12-23 8:52:36      0:31:19        16    134
3    2016-12-23 8:52:36      0:31:19        16    134
4     2016-12-25 8:0:51      0:30:10        50    135
5     2016-12-25 8:0:51      0:30:10        50    135
6    2016-12-26 8:41:26       0:10:1        27    116
7    2016-12-26 8:41:26       0:10:1        27    116
8      2017-1-7 11:16:9      0:26:15        22    124
9      2017-1-7 11:16:9      0:26:15        22    124
10    2017-1-10 19:2:54      0:53:51         5    142
11    2017-1-10 19:2:54      0:53:51         5    142

我一直在尝试格式化此列H:M:S格式 使用

timeDF=(pd.to_datetime(cleanDF['Running-Time'],format='%H:%M:%S'))

但我一直在得到ValueError: time data ' 0:24:2' does not match format '%M:%S' (match) this error

先感谢您。


尾随空格有问题,所以需要str.strip http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.strip.html:

或者如果创建DataFrame从文件中read_csv http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html添加参数skipinitialspace=True:

cleanDF = pd.read_csv(file, skipinitialspace = True)

timeDF=(pd.to_datetime(cleanDF['Running-Time'].str.strip(), format='%H:%M:%S'))
print (timeDF)
0    1900-01-01 00:24:02
1    1900-01-01 00:24:02
2    1900-01-01 00:31:19
3    1900-01-01 00:31:19
4    1900-01-01 00:30:10
5    1900-01-01 00:30:10
6    1900-01-01 00:10:01
7    1900-01-01 00:10:01
8    1900-01-01 00:26:15
9    1900-01-01 00:26:15
10   1900-01-01 00:53:51
11   1900-01-01 00:53:51
Name: Running-Time, dtype: datetime64[ns]

但也许更好的方法是将其转换为时间增量to_timedelta http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html:

timeDF=(pd.to_timedelta(cleanDF['Running-Time'].str.strip()))
print (timeDF)
0    00:24:02
1    00:24:02
2    00:31:19
3    00:31:19
4    00:30:10
5    00:30:10
6    00:10:01
7    00:10:01
8    00:26:15
9    00:26:15
10   00:53:51
11   00:53:51
Name: Running-Time, dtype: timedelta64[ns]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Pandas 将列转换为时间 的相关文章

随机推荐