3 回答

TA貢獻1868條經驗 獲得超4個贊
嘗試apply:
def f(x):
if x >= 7:
SID = 3
elif x >= 6 and x<7:
SID = 2
else:
SID = 1
return SID
df['SID']=df['order_total'].apply(f)

TA貢獻1806條經驗 獲得超5個贊
使用 groupby 和 transform 來獲取包含每個 consumer_id 的平均訂單總數(shù)的系列,然后將函數(shù)應用于該系列以創(chuàng)建結果系列。
def sid_assign(x):
if x >= 7:
return 3
if x >= 6 | x < 7:
return 2
else:
return 1
id_sums = df.groupby('consumer_id').order_total.transform('mean')
df['SID'] = id_sums.apply(sid_assign)
print(df)
consumer_id order_total SID
0 1 5 1
1 2 6 2
2 3 7 3
3 1 5 1
添加回答
舉報