如何将字符串格式的时间转换为 pandas 中的时间?

How to convert a time with string format to Time in pandas?

有一个数据框,其列 timestringdateint 从 1 到 140。

时间是一个字符串:

0         00:05:24
1         00:05:43
2         00:06:34
3         00:06:50
4         00:06:55

我想创建一个 Random Forest 的模型来预测 class h,但是我们可以看到日期和时间列没有用,我不能在 Random Forest。我需要以某种方式将这两列组合成一个新列,使它们在预测中有用。

如果您想将所有内容都保留为数字特征,那么无论日期代表什么(我假设您是相对于某个零点对天数进行编号?),您可以将时间添加为一天的一小部分(时间在秒/一天中的秒数)。

虚拟数据:

>>> df
13:    date      time
0    23  00:05:43
1    45  00:06:34
2    67  00:06:50
3    89  00:06:55

计算时间分数,把它加到日期上得到'time':

>>> df['seconds'] = df.time.apply(pd.to_timedelta).apply(lambda x: x.total_seconds())
>>> df['of_day'] = df.seconds / (24*60*60)
>>> df['datetime_number'] = df.date + df.of_day
>>> df
17:    date      time  seconds    of_day  datetime_number
0    23  00:05:43    343.0  0.003970        23.003970
1    45  00:06:34    394.0  0.004560        45.004560
2    67  00:06:50    410.0  0.004745        67.004745
3    89  00:06:55    415.0  0.004803        89.004803