Reputation: 13
I am trying to create a column that is true if it is in leap year and false otherwise.
This is what I have tried so far and struggling to combined into one column:
df = pd.read_csv("https://raw.githubusercontent.com/selva86/datasets/master/AirPassengers.csv")
"""
Here are the rules of leap years:
A year may be a leap year if it is evenly divisible by 4.
Years that are divisible by 100 (century years such as 1900 or 2000) cannot be leap years unless they are also divisible by 400. (For this reason, the years 1700, 1800, and 1900 were not leap years, but the years 1600 and 2000 were.)
condiction:
1) divisible by 4
2) check century: divsible by 100 & 400
"""
df['year']=pd.to_datetime(df.date).dt.year
def filter_func(x):
if x[2] % 4 ==0:
return True
else:
return False
def filter_func1(x):
if x[2] % 100 ==0 and x[2] %400 ==0:
return True
else:
return False
df['multi_true'] = df.apply(filter_func1, axis=1)
Upvotes: 1
Views: 62
Reputation: 71610
Pandas already has a function for this:
df['multi_true'] = pd.to_datetime(df['year'], format='%Y').dt.is_leap_year
It would give false for 1900
as well.
Upvotes: 4