我有一个日期如下的数据框:
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中仅传递一组值时,它可以工作,因此我的公式绝对正确。创建另一个带有日期偏移的列,然后应用公式确实可以,但是我正在寻找一种更简洁的方法。我不确定应用功能。我应该有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 :(得分:1)
使用pd.to_datetime
将系列转换为类似系列的日期时间,然后使用Series.dt
访问系列的日期时间属性,然后在组件year
,{{1 }}和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
答案 1 :(得分:0)
如果要使用.apply
,则需要修改函数(或基于已有的函数添加另一个函数)以对Series对象(而不是其元素)进行操作。请参见pandas DataFrame apply docstring“传递给函数的对象是Series对象,其索引为
要么...”
您可以通过使用列表理解来避免使用.apply和lambda
df['derived'] = [ yourfunction(a,b) for a,b in zip(df.index, df.index.shift(-1)) ]
我确定还有另一种向量化函数的方法,但这至少应该使您的代码正常工作。曾经有一段时间,lambda表达式遭到python的关键人物的强烈反对,并提倡将其删除,因为它总是可以用另一种方法完成的。