[英]Pandas apply based on conditional from another column
我想根據另一列中的條件調整一列的值。
我正在使用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,但無濟於事。
可以肯定這是可行的,但是還有更多優化的實現:
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)
for
你的代碼可以通過該行進行更換:
dispdf.loc[dispdf.dayofweek>5,'dispatch_working_days']+=1
或者你可以使用numpy.where
https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.