Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete leap days in pandas

I have a data frame in pandas like this:

    ID          Date        Element Data_Value
0   USW00094889 2014-11-12  TMAX    22
1   USC00208972 2009-04-29  TMIN    56
2   USC00200032 2008-05-26  TMAX    278
3   USC00205563 2005-11-11  TMAX    139
4   USC00200230 2014-02-27  TMAX    -106

I want to remove all leap days and my code is

df = df[~((df.Date.month == 2) & (df.Date.day == 29))]

but the AttributeError happened :

'Series' object has no attribute 'month'

Whats wrong with my code?

like image 557
JAKE Avatar asked Jan 05 '19 12:01

JAKE


2 Answers

Use dt accessor:

df = df[~((df.Date.dt.month == 2) & (df.Date.dt.day == 29))]
like image 190
U12-Forward Avatar answered Sep 30 '22 14:09

U12-Forward


Add dt accessor because working with Series, not with DatetimeIndex:

df = df[~((df.Date.dt.month == 2) & (df.Date.dt.day == 29))]

Or invert condition with chaining | for bitwise OR and != for not equal:

df = df[(df.Date.dt.month != 2) | (df.Date.dt.day != 29)]

Or use strftime for convert to MM-DD format:

df = df[df.Date.dt.strftime('%m-%m') != '02-29'] 
like image 32
jezrael Avatar answered Sep 30 '22 13:09

jezrael