如何删除特定列值不是date且所有列都是字符串类型的行

2024-09-30 01:20:01 发布

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

我有这样一个数据框:

df
col1          col2      col3
01/01/10      abc       pqr
10/10/18      sps       ggg
date          pqp       fdf
03/12/19      rt        sd
summary       re        ss

所有列都是字符串类型,我想删除那些值不是任何日期的行

输出df应该如下所示

df
col1          col2      col3
01/01/10      abc       pqr
10/10/18      sps       ggg
03/12/19      rt        sd

如何在python中以最有效的方式完成它


Tags: 数据dfdatesdsummarycol2col3col1
2条回答

可以将^{}errors=‘coerce’一起使用: 从文档中:

If ‘coerce’, then invalid parsing will be set as NaT

df.loc[pd.to_datetime(df.col1,errors='coerce').dropna().index]

       col1 col2 col3
0  01/01/10  abc  pqr
1  10/10/18  sps  ggg
3  03/12/19   rt   sd

或者,如果希望col1成为datetime列,请使用:

df.col1=pd.to_datetime(df.col1,errors='coerce')
df[df.col1.notna()]

使用re.findall

df2[df2.apply(lambda x: True if len(re.findall('\d{2}/\d{2}/\d{2}',x.col1)) >= 1 else False, axis=1)]

输出

      col1 col2 col3
0  01/01/10  abc  pqr
1  10/10/18  sps  ggg
3  03/12/19  rt   sd

相关问题 更多 >

    热门问题