2

我有数据框 x,

请在此处查看 x 数据框

我们想使用以下函数创建新列,它将在开始时添加完整列值并创建新列完成。

import datetime
def date_by_adding_business_days(from_date, add_days):
    business_days_to_add = add_days
    current_date = from_date
    while business_days_to_add > 0:
        current_date += datetime.timedelta(days=1)
        weekday = current_date.weekday()
        if weekday >= 5: # sunday = 6
            continue
        business_days_to_add -= 1
    return current_date

我试过这个低于错误,请帮助。

x['Finish'] = x.apply(date_by_adding_business_days(datetime.date.today(), x['Complete']))

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
4

3 回答 3

2

你的方法是正确的。您只需要传递函数引用即可。

当你打电话申请时。它将数据帧行传递给函数并调用它。

您可以在函数本身内计算变量,例如今天的日期

def date_by_adding_business_days(row):
    add_days = row['Complete']
    from_date = datetime.date.today()

    business_days_to_add = add_days
    current_date = from_date
    while business_days_to_add > 0:
        current_date += datetime.timedelta(days=1)
        weekday = current_date.weekday()
        if weekday >= 5:  # sunday = 6
            continue
        business_days_to_add -= 1
    return current_date

x['Finish'] = x.apply(date_by_adding_business_days, axis=1)
于 2020-05-07T08:06:21.357 回答
2

尝试重构您的代码。如果您仅将功能应用于一列,那么您做错了。此外,由于某种原因,您试图调用传递时间给它的函数。为什么如果你能在函数中得到它:

import datetime
def date_by_adding_business_days(add_days):
    business_days_to_add = add_days
    current_date = datetime.date.today()
    while business_days_to_add > 0:
        current_date += datetime.timedelta(days=1)
        weekday = current_date.weekday()
        if weekday >= 5: # sunday = 6
            continue
        business_days_to_add -= 1
    return current_date

x['Finish'] = x['Complete'].apply(date_by_adding_business_days)
于 2020-05-07T08:05:11.330 回答
0

尽管上述两种方法都可以达到目的,但我认为第二个选项在 apply() 对单列的行执行时更快。如果您根据问题中提供的示例数据框在笔记本中对这些解决方案进行计时,则差异似乎很明显。

附上截图。 计时 apply() 函数

于 2020-05-07T08:33:43.363 回答