问题描述
我是 Python 新手。我有一个数据框,其中有一个日期列,它有不同的格式。我想检查它是否遵循特定的日期格式。我没有跟随我想放弃它。我试过使用 try except 并遍历行。但我正在寻找一种更快的方法来检查该列是否遵循特定的日期格式。 If it is not following then it has to drop. Is there any faster way to do it? Using DATE TIME library?
My code:
Date_format = %Y%m%d
df =
Date abc
0 2020-03-22 q
1 03-12-2020 w
2 55552020 e
3 25122020 r
4 12/25/2020 r
5 1212202033 y
Excepted out:
Date abc
0 2020-03-22 q
解决方法
你可以试试
pd.to_datetime(df.Date,errors='coerce')
0 2020-03-22
1 2020-03-12
2 NaT
3 NaT
4 2020-12-25
5 NaT
然后很容易删除空值
编辑:
对于给定的格式,您仍然可以利用 pd.to_datetime
:
datetimes = pd.to_datetime(df.Date,format='%Y-%m-%d',errors='coerce')
datetimes
0 2020-03-22
1 NaT
2 NaT
3 NaT
4 NaT
5 NaT
df.loc[datetimes.notnull()]
另请注意,我正在使用 %Y-%m-%d
格式,根据您的预期输出,我认为这是您想要的格式(而不是您提供的格式为 Date_format
)