Home > Blockchain >  How to check if dates in a pandas column are after a date
How to check if dates in a pandas column are after a date

Time:11-24

I have a pandas dataframe

      date       
0     2010-03  
1     2017-09-14     
2     2020-10-26      
3     2004-12     
4     2012-04-01      
5     2017-02-01      
6     2013-01

I basically want to filter where dates are after 2015-12 (Dec 2015)

To get this:

      date       
0     2017-09-14     
1     2020-10-26          
2     2017-02-01  

I tried this

df = df[(df['date']> "2015-12")]

but I'm getting an error

ValueError: Wrong number of items passed 17, placement implies 1

CodePudding user response:

First for me working solution correct:

df = df[(df['date']> "2015-12")]
print (df)
         date
1  2017-09-14
2  2020-10-26
5  2017-02-01

If convert to datetimes, which should be more robust for me working too:

df = df[(pd.to_datetime(df['date'])> "2015-12")]
print (df)
         date
1  2017-09-14
2  2020-10-26
5  2017-02-01

Detail:

print (pd.to_datetime(df['date']))
0   2010-03-01
1   2017-09-14
2   2020-10-26
3   2004-12-01
4   2012-04-01
5   2017-02-01
6   2013-01-01
Name: date, dtype: datetime64[ns]
  • Related