我們有在線訂單資料,其中包含訂單級別的總運費,但我們的會計師需要將總運費分攤給多個供應商,并在行級別細分。
不是每個產品都有運費,有些產品有促銷免費送貨,這需要在拆分運費時考慮(當商品不發貨或免費送貨時,不要考慮運費)。
我創建了這個測驗,它產生了預期的結果(對另一位同事進行作業的大道具),但想了解是否有更有效的(pythonic!)方法來實作這一點。
這以前是通過 odbc 連接到 sql 資料庫完成的,并使用 excel 公式處理。
import pandas as pd
import numpy as np
df = pd.DataFrame({'id': [10, 11, 11, 11, 12, 12, 13, 14, 15, 15],
'shipping': [5, 5, 5, 5, 5, 5, 0, 0, 5, 5],
'shipstatus': [True, True, True, False,
True, True, False, True, True, True],
'freeship': [False, True, False, False,
False, False, False, True, False, False]})
df['a'] = df.groupby(['id','shipstatus','freeship'])['shipping'].transform('count')
# the final step of the excel code is counting (grouping) by id and shipstatus,
# so we group those here. we also group by freeship so that the count of id/shipstatus
# won't be included when freeship is true (which we zero out later)
df['b'] = df['a'] * (df['freeship']==False)
# if freeship is true, second piece evaluates to false, whole thing evaluates to zero
df['c'] = df['shipping']/df['b']
# this will give you inf where we set stuff to zero above.
# you'll also get NaN when 'shipping' is zero
df['LineShipping'] = df['shipstatus'] * (df['freeship']==False) * df['c']
# sets the whole thing to zero if freeship is true or shipstatus is false,
# otherwise multiplies our # previous result by 1 and so no change
df = df.fillna(0)
# sets all the NaN to zero
df = df.drop(columns=['a','b','c'])
# saves the dataframe but with the temp columns dropped
print(df)

uj5u.com熱心網友回復:
所以基本上你要分發的shipping內id與行之間均勻shipstatus==True和freeship==False。當shipstatus==False或 時freeship==True,LineShipping==0總是。
因此,您可以計算/劃分您的條件。這樣,您就不會收到除以零的警告:
counts = (df[df['shipstatus'] & ~df['freeship']] # only count when shipstatus == True and freeship == False
.groupby(['id']) # no need to groupby shipstatus
['shipping'].transform('size') # size or count
)
# only divide where `shipstatus==True` and `freeship==False`, else is `NaN`
# then fillna with 0
df['LineShipping'] = df['shipping'].div(counts).fillna(0)
輸出:
id shipping shipstatus freeship LineShipping
0 10 5 True False 5.0
1 11 5 True True 0.0
2 11 5 True False 5.0
3 11 5 False False 0.0
4 12 5 True False 2.5
5 12 5 True False 2.5
6 13 0 False False 0.0
7 14 0 True True 0.0
8 15 5 True False 2.5
9 15 5 True False 2.5
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/349878.html
