对熊猫数据框的了解-
我有这样一种日期格式:datetime64[ns]
和一列int64
格式。
数据框如下所示:
date days
0 2019-07-04 1
1 2019-10-17 1
2 2019-10-17 2
我想使用此功能添加n个工作日:
def add_business_days(from_date,ndays):
business_days_to_add = abs(ndays)
current_date = from_date
sign = ndays/abs(ndays)
while business_days_to_add > 0:
current_date += datetime.timedelta(sign * 1)
weekday = current_date.weekday()
if weekday >= 5: # sunday = 6
continue
business_days_to_add -= 1
return current_date
但是我莫名其妙地得到了这个错误:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
您能帮上忙吗?
答案 0 :(得分:1)
pandas
在工作日提供了已实施的支持。我不确定您的输出应该是什么样子(因为您没有包括预期的输出,可以添加吗?),但是我想这就是您想要的:
pd.to_datetime(from_date) + pd.offsets.BDay(ndays)
假设您的数据框如下所示:
dates = [pd.to_datetime('2019-07-04'), pd.to_datetime('2019-10-17'), pd.to_datetime('2019-10-17')]
df = pd.DataFrame(data={'date': dates, 'days': [1, 1, 2]})
可以省略到pd.to_datetime()
的时间戳转换。
答案 1 :(得分:1)
在offsets.BDay
中使用lambda函数:
def add_business_days(from_date,ndays):
return from_date + pd.offsets.BDay(ndays)
df['date'] = pd.to_datetime(df['date'])
df['new'] = df.apply(lambda x: add_business_days(x['date'], x['days']), axis=1)
或者:
df['new'] = df.apply(lambda x: x['date'] + pd.offsets.BDay(x['days']), axis=1)
print (df)
date days new
0 2019-07-04 1 2019-07-05
1 2019-10-17 1 2019-10-18
2 2019-10-17 2 2019-10-21