当同一列具有不同格式时,在数据帧上转换日期格式

2024-10-01 09:23:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python工作,我正在加载一个文件并将其保存在一个如下所示的数据帧中。你知道吗

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-yyyydd/mm/yyyy,我需要它将其转换为datetime。你知道吗

我试过做转换,但是这个转换是用dd/mm/yyyy格式转换为NaT日期的

enter image description here

我怎样才能解决这个问题?你知道吗


Tags: 文件数据nodatetime格式natddmm
2条回答

用途:

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

让熊猫猜猜看:

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]

相关问题 更多 >