基于另一列的条件进行 Pandas 的 apply 操作

4

我希望根据另一列的条件来调整一列值。

我正在使用np.busday_count,但是我不希望周末的值像周一那样(把周六到周二视为一个工作日,我希望将其视为两个)。

dispdf = df[(df.dispatched_at.isnull()==False) & (df.sold_at.isnull()==False)]

dispdf["dispatch_working_days"] = np.busday_count(dispdf.sold_at.tolist(), dispdf.dispatched_at.tolist())

for i in range(len(dispdf)):
    if dispdf.dayofweek.iloc[i] == 5 or dispdf.dayofweek.iloc[i] == 6:
        dispdf.dispatch_working_days.iloc[i] +=1

示例:

            dayofweek   dispatch_working_days
    43159   1.0 3
    48144   3.0 3
    45251   6.0 1
    49193   3.0 0
    42470   3.0 1
    47874   6.0 1
    44500   3.0 1
    43031   6.0 3
    43193   0.0 4
    43591   6.0 3

预期结果:
        dayofweek   dispatch_working_days
43159   1.0 3
48144   3.0 3
45251   6.0 2
49193   3.0 0
42470   3.0 1
47874   6.0 2
44500   3.0 1
43031   6.0 2
43193   0.0 4
43591   6.0 4

目前我正在使用这个for循环向星期六和星期日的值添加工作日。但是这个方法速度很慢!

我能否使用矢量化来加速这个过程呢?我尝试使用.apply,但没有成功。


你能发布一下你想要看到的结果吗? - joaoavf
1
是的,已经添加了。基本上,任何 dayofweek 行等于 5 或 6 的行都需要将 dispatch_working_days 的值增加 +1。 - Leon Kyriacou
2个回答

3

我相信这个方案可行,但还有更优化的实现方法:

def adjust_dispatch(df_line):
    if df_line['dayofweek'] >= 5:
        return df_line['dispatch_working_days'] + 1
    else:
        return df_line['dispatch_working_days']         

df['dispatch_working_days'] = df.apply(adjust_dispatch, axis=1)

2

我认为这些代码行可以让你的程序运行更快:dispdf = df.dropna(subset=['dispatched_at','sold_at']) dispdf["dispatch_working_days"] = np.busday_count(dispdf.sold_at.values.astype('datetime64[D]'),dispdf.dispatched_at.values.astype('datetime64[D]')) - ilia timofeev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接