熊猫基于另一列的条件申请

2024-04-19 20:48:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我在用np.busday_计数,但我不希望周末值表现得像星期一(周六到周二是1个工作日,我希望是2个工作日)

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

样品:

^{pr2}$

预期结果:

        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循环将工作日添加到星期六和星期日的值。太慢了!在

我可以用矢量化来加快速度吗。我试着用。申请但没用。在


Tags: falsedfnpdaysatworkingdispatch工作日
2条回答

代码中的for可以替换为以下行: 在

dispdf.loc[dispdf.dayofweek>5,'dispatch_working_days']+=1

或者您可以使用numpy.where

https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html

很肯定这是可行的,但还有更优化的实现:

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)

相关问题 更多 >