我有一个包含日期的DataFrame:
Daycount
Date
2020-05-01 0
2020-06-01 0
2020-07-01 0
2020-08-01 0
2020-09-01 0
我尝试使用以下公式提取从一天到下一天的日计数:
def days360(start_date, end_date, method_eu=False):
start_day = start_date.day
start_month = start_date.month
start_year = start_date.year
end_day = end_date.day
end_month = end_date.month
end_year = end_date.year
if start_day == 31 or (method_eu is False and start_month == 2 and (start_day == 29 or (start_day == 28 and calendar.isleap(start_year) is False))):
start_day = 30
if end_day == 31:
if method_eu is False and start_day != 30:
end_day = 1
if end_month == 12:
end_year += 1
end_month = 1
else:
end_month += 1
else:
end_day = 30
return end_day + end_month * 30 + end_year * 360 - start_day - start_month * 30 - start_year * 360
然而,我尝试按照以下方式使用apply函数,但是出现了以下错误:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
在DataFrame中只传递一个值集合时,它可以工作,因此我的公式肯定是正确的。创建另一个带有移动日期的列,然后应用该公式确实可行,但我正在寻找更简洁的方法。不过,我对apply函数还不确定。我应该为所有daycount获得30天。
hypo["Daycount"] = hypo.apply(lambda x: days360(x.index,x.index.shift(-1)))
期望的输出应该是下面的表格:
Date Daycount
0 2020-05-01 30.0
1 2020-06-01 30.0
2 2020-07-01 30.0
3 2020-08-01 30.0
4 2020-09-01 30.0
[0, 31.0, 30.0, 31.0, 31.0]
。 - Shubham Sharma