删除X列为日期时间的数据框中的行

时间:2020-10-30 09:15:29

标签: python pandas dataframe

我需要删除X列为日期时间的行。

我已经尝试过了

from pandas.api.types import is_datetime64_any_dtype as is_datetime
indexNames = df[is_datetime(df['Column X'])].index
df.drop(indexNames, inplace=True)

但返回

KeyError:错误

以下方法也不起作用(无错误)

indexNames = df[df['Column X'] == is_datetime(df['Column X'])].index

我仍然具有类似datetime.datetime(2016,6,29,8,24,19)的值

我发现了一个相关的问题,但是倒转了Pandas delete all rows that are not a 'datetime' type

请问您有什么主意吗?

1 个答案:

答案 0 :(得分:1)

to_datetimeerrors='coerce'一起用于将非datetimelike转换为NaN,因此请在Series.isna中按boolean indexing进行过滤:

df = df[pd.to_datetime(df['Column X'], errors='coerce').isna()]

但是有时熊猫会在日期时间识别一些2000之类的整数,因此,如果可能的话,更精确的方法是指定日期时间的格式,例如这里YYYY-MM-DD

df = df[pd.to_datetime(df['Column X'], errors='coerce', format='%Y-%m-%d').isna()]