【问题标题】:Pandas apply based on conditional from another columnPandas 根据另一列的条件应用
【发布时间】:2018-02-20 03:42:35
【问题描述】:

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

我正在使用 np.busday_count,但我不希望周末值表现得像星期一(星期六到星期二有 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

示例:

            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 但无济于事。

【问题讨论】:

  • 你能发布你想看的结果吗?
  • 是的,添加进去了。基本上,dayofweek 中任何等于 5 或​​ 6 的行都需要将 dispatch_working_days 的值增加 +1

标签: python pandas


【解决方案1】:

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

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】:

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

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

    或者你可以使用numpy.where

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

    【讨论】:

    • 我认为这行代码可以给你一些加速: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]'))
    猜你喜欢
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-09
    • 2020-08-20
    • 1970-01-01
    • 2019-10-31
    相关资源
    最近更新 更多