Adit2789
Adit2789

Reputation: 149

How to check if years in a pandas dataframe column are leap years - Python

I have a data set that looks like:

        DOB    DOB_year
0      1964-01-06  1964
1      1984-01-13  1984
2      1992-01-20  1992
3      1972-01-27  1972
4      2001-02-03  2001
5      2011-02-10  2011
6      1950-02-17  1950
7      1968-02-24  1968

    [318495 rows x 2 columns]

I want an output like:

             DOB       DOB_year      is_leap
    0      1964-01-06  1964           TRUE
    1      1983-01-13  1984           FALSE
    2      1992-01-20  1992           TRUE
    3      1972-01-27  1972           TRUE
    4      2001-02-03  2001           FALSE
    5      2011-02-10  2011           FALSE
    6      1950-02-17  1950           FALSE
    7      1968-02-24  1968           TRUE

Below is the code:

def is_leapCheck(s):
return (s.dt.year % 4 == 0) & ((s.dt.year % 100 != 0) | (s.dt.year % 400 == 0)) & (s.dt.month == 2) & (s.dt.day == 29)

dob_df['is_leap']=is_leapCheck(pd.to_datetime(dob_df['year']))

The output of the code has all the_leap values as FALSE and no TRUE values at all. I am not sure where i am going wrong on this. Any help appreciated

Upvotes: 0

Views: 1590

Answers (2)

user3483203
user3483203

Reputation: 51165

Your condition is slightly off, but here is a solution using the language-agnostic way of determining if a year is a leap year:

condition = (df.DOB.dt.year.mod(4).eq(0) 
    & (df.DOB.dt.year.mod(100).ne(0) | df.DOB.dt.year.mod(400).eq(0))
)

df.assign(isleap=np.where(condition, 'TRUE', 'FALSE'))

         DOB  DOB_year isleap
0 1964-01-06      1964   TRUE
1 1984-01-13      1984   TRUE
2 1992-01-20      1992   TRUE
3 1972-01-27      1972   TRUE
4 2001-02-03      2001  FALSE
5 2011-02-10      2011  FALSE
6 1950-02-17      1950  FALSE
7 1968-02-24      1968   TRUE

Upvotes: 1

Dani Mesejo
Dani Mesejo

Reputation: 61920

You could use the calendar module as in the following (toy) example:

import calendar
import pandas as pd


frame = pd.DataFrame(data=[2012], columns=['year'])
frame['is_leap'] = frame['year'].apply(lambda e: calendar.isleap(e))
print(frame)

Output

   year  is_leap
0  2012     True

Upvotes: 2

Related Questions