如何将数据帧转换为数据时间格式?

问题描述 投票:0回答:1

我有这个数据框。

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秒,就会自动增加分钟。如果是64秒,应该是这样的: 2020-03-21 19:60:04.

任何帮助将被感激。

python-3.x pandas data-science datetime-format
1个回答
1
投票

首先通过以下方式转换日期时间 to_datetime 有格式和 errors='coerce' 参数,所以缺失值为不匹配值。然后转发填充它们,以便重复 datetimes.

然后进行处理 seconds - 先将其转换为数字 to_numeric,然后通过 to_timedelta 和最后添加到datetimes。

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
© www.soinside.com 2019 - 2024. All rights reserved.