如何使用闰年逻辑在单个数据框列中应用多个条件



我正在尝试创建一个列,如果它是在闰年为真,否则为假。

这是我到目前为止尝试并努力合并成一列的内容:

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)

Pandas已经提供了一个函数:

df['multi_true'] = pd.to_datetime(df['year'], format='%Y').dt.is_leap_year

对于1900,它也会给出false。

最新更新