简体   繁体   中英

Drop rows with datetime condition in pandas

I have a dataset with 14 columns and with more than 1000 rows.

I am trying to drop rows that have value before 1/1/2015 from column DATE. First, I manipulated the columns DATE by doing this:

import pandas as pd

from datetime import date

df['DATE'] =  pd.to_datetime('DATE'], infer_datetime_format=True)

Then, trying to drop rows with this script:

df.drop( df[ df['DATE'] < pd.Timestamp(date(2015,1,1)) ].index, inplace=True)

But it returns:

KeyError: 'DATE'

Your code actually works, but the pd.to_datetime has a small typo:

df = pd.DataFrame({'ID': [1,2], 'DATE': ['2002-11-7', '2020-7-27']})

df['DATE'] =  pd.to_datetime(df['DATE'], infer_datetime_format=True)

df.drop( df[ df['DATE'] < pd.Timestamp(date(2015,1,1)) ].index, inplace=True)

Removing date in the argument of Timestamp works for me.

Try this:

df.drop( df[ df['DATE'] < pd.Timestamp(2015,1,1) ].index, inplace=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM