我正在使用pandas python,并且正在加载文件并将其保存在如下所示的DataFrame中。
27 9-7-2019 30.029 MOROSO MOVIL NO 30029
28 9-7-2019 40.575 MOROSO MOVIL NO 40575
29 9-7-2019 31.929 MOROSO MOVIL NO 31929
30 9-7-2019 133.53 MOROSO MOVIL NO 133530
31 9-7-2019 62.426 MOROSO MOVIL NO 62426
.. ... ... ... ... ... ...
476 9/7/2019 34.397 MOROSO MOVIL NO 34397
477 9/7/2019 89.827 MOROSO MOVIL NO 89827
478 9/7/2019 37.973 MOROSO MOVIL NO 37973
479 9/7/2019 29.98 MOROSO MOVIL NO 29980
480 9/7/2019 25.992 MOROSO MOVIL NO 25992
问题出在第二列中,日期以不同的格式dd-mm-yyyy
和dd/mm/yyyy
出现,我需要将其转换为日期时间。
我尝试进行转换,但是将转换为NaT的日期格式为dd/mm/yyyy
我该如何解决?
答案 0 :(得分:1)
只要让熊猫猜:
df['due-date'] = pd.to_datetime(df['due-date'])
输出:
0 2019-09-07
1 2019-09-07
2 2019-09-07
3 2019-09-07
4 2019-09-07
5 2019-09-07
6 2019-09-07
7 2019-09-07
8 2019-09-07
9 2019-09-07
Name: due-date, dtype: datetime64[ns]
答案 1 :(得分:0)
使用:
df['date'] = df['date'].str.replace('/', '-')
df['date'] = pd.to_datetime(df['date'])
输出:
0 27 2019-09-07 30.029 MOROSO MOVIL NO 30029
1 28 2019-09-07 40.575 MOROSO MOVIL NO 40575
2 29 2019-09-07 31.929 MOROSO MOVIL NO 31929
3 30 2019-09-07 133.530 MOROSO MOVIL NO 133530
4 31 2019-09-07 62.426 MOROSO MOVIL NO 62426
5 476 2019-09-07 34.397 MOROSO MOVIL NO 34397
6 477 2019-09-07 89.827 MOROSO MOVIL NO 89827
7 478 2019-09-07 37.973 MOROSO MOVIL NO 37973
8 479 2019-09-07 29.980 MOROSO MOVIL NO 29980
9 480 2019-09-07 25.992 MOROSO MOVIL NO 25992