我有一个日期如下的 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
但是,我尝试使用如下的应用函数,但我得到以下错误:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
当只在 DataFrame 中传递一组值时,它起作用了,所以我的公式绝对正确。创建日期偏移的另一列,然后应用公式确实有效,但我正在寻找一种更简洁的方法。我不确定应用功能。我应该得到 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
最佳答案
使用,pd.to_datetime
将系列转换为日期时间系列,然后使用 Series.dt
访问系列的日期时间属性,然后使用 Series.diff
在组件 year
、month
和 day
上获得所需的结果:
df = df.reset_index()
dates = pd.to_datetime(df['Date'])
df['Daycount'] = (
(dates.dt.year.diff() * 360 + dates.dt.month.diff() * 30 + dates.dt.day.diff()).fillna(0)
)
# print(df)
Date Daycount
0 2020-05-01 0.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
考虑另一个具有更复杂数据框的示例:
# Given dataframe
# print(df)
Daycount
Date
2020-05-01 0
2020-06-03 0
2020-07-01 0
2021-07-02 0
2022-08-03 0
# Desired result
# print(df)
Date Daycount
0 2020-05-01 0.0
1 2020-06-03 32.0
2 2020-07-01 28.0
3 2021-07-02 361.0
4 2022-08-03 391.0
关于python - 使用 pandas apply with dates and dates shifted,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62405054/