我有这个数据框:
3_21_19_59
1
4
22
25
28
31
34
37
.
.
.
.
它有410行。
在3_21_19_59
中:3
表示月份,21
表示日期,19
是小时,59
是分钟。下面的行中的数字:1
,4
,22
...是秒。
现在,我想将此数据帧转换为这样的日期时间格式:
2020-03-21 19:59:00
2020-03-21 19:59:01
2020-03-21 19:59:04
2020-03-21 19:59:22
2020-03-21 19:59:25
2020-03-21 19:59:28
...
...
...
,依此类推。 60秒后,分钟应自动增加。例如:如果是64秒,则应类似于2020-03-21 19:60:04
。
任何帮助将不胜感激。
答案 0 :(得分:1)
首先使用格式和errors='coerce'
参数用to_datetime
转换日期时间,因此缺少不匹配值的值。然后转发fillinf以拒绝datetimes
。
然后处理seconds
-首先由to_numeric
转换为数字,然后由to_timedelta
转换为timedelta,最后将其添加到日期时间:
print (df)
col
0 3_21_19_59
1 1
2 4
3 22
4 25
5 28
6 31
7 34
8 37
d = pd.to_datetime('20_' + df['col'], format='%y_%m_%d_%H_%M', errors='coerce').ffill()
td = pd.to_numeric(df['col'], errors='coerce').fillna(0)
df['col'] = d.add(pd.to_timedelta(td, unit='s'))
print (df)
col
0 2020-03-21 19:59:00
1 2020-03-21 19:59:01
2 2020-03-21 19:59:04
3 2020-03-21 19:59:22
4 2020-03-21 19:59:25
5 2020-03-21 19:59:28
6 2020-03-21 19:59:31
7 2020-03-21 19:59:34
8 2020-03-21 19:59:37