如何忽略无法转换为datetime的列单元格以计算时间d

2024-09-29 06:25:56 发布

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

我有一个df

doc_date    date_string
2019-06-03  WW0306
2019-06-07  EH0706
2019-08-08  19685
2019-08-09  258
2019-08-10  441573556

doc_datedateimte64数据类型,date_stringstring,删除非数字字符

s = df['date_string'].str.replace(r'\D+', '')

doc_date    date_string
2019-06-03  0306
2019-06-07  0706
2019-08-08  19685
2019-08-09  258
2019-08-10  441573556

s1 = to_datetime(s, errors='ignore', format='%d%m')

doc_date    date_string
2019-06-03  1900-06-03
2019-06-07  1900-06-07
2019-08-08  19685
2019-08-09  258
2019-08-10  441573556

这里我想知道如何忽略那些date_string不能转换为datetime的行;所以我可以创建一个布尔掩码

 c1 = (df.doc_date.dt.dayofyear - s1.dt.dayofyear).abs().le(180)

另一件事是如何获得c1s相同的长度,任何date_string不能转换成datetimeFalsec1


Tags: dfdatetimedatestringdocdt数字字符
1条回答
网友
1楼 · 发布于 2024-09-29 06:25:56

使用errors='coerce'将不匹配的模式值转换为NaT工作日期时间型函数:

s1 = to_datetime(s, errors='coerce', format='%d%m')

或更常用(0.24.2,所以输出不同):

import pandas as pd

s1 = pd.to_datetime(s, errors='coerce', format='%d%m')
print (s1)
0   1900-06-03
1   1900-06-07
2          NaT
3   1900-08-25
4          NaT
Name: date_string, dtype: datetime64[ns]

总之:

#if necessary
#df['doc_date'] =  pd.to_datetime(df['doc_date'])

s = df['date_string'].str.replace(r'\D+', '')

s1 = pd.to_datetime(s, errors='coerce', format='%d%m')

c1 = (df.doc_date.dt.dayofyear - s1.dt.dayofyear).abs().le(180)
print (c1)
0     True
1     True
2    False
3     True
4    False
dtype: bool

相关问题 更多 >