delete leap days in pandas

Viewed 2270

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?

3 Answers

Use dt accessor:

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

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'] 

Another way you can try below in incase your Date column is not proper datetime rather a str.

df[~df.Date.str.endswith('02-29')]

OR , if it's in datetime format even you can try converting to str.

df[~df.Date.astype(str).str.endswith('02-29')]

OR, Even use contains:

df[~df.Date.str.contains('02-29')]
Related