我正在嘗試在 Python 中對分組資料框執行 case when/if-else 陳述句以創建新變數。如果我在 R 中編碼并且我正在嘗試在 Python 中找到一個相似且矢量化的操作,我會想要執行以下操作。代碼:
dt %>% group_by(user,merchant,date) %>%
mutate(
new_variable = case_when(-amount == lag(amount) ~ 2,
True ~ 1)
) %>% ungroup()
在 Python 中,我嘗試使用 np.select:
conditions = [
(-us_trans['real_amount'] == us_trans['real_amount'].shift(-1)),
(-us_trans['real_amount'] != us_trans['real_amount'].shift(-1))
]
values = [
2,
1
]
但我不知道如何在分組資料框中使用 np.select 來創建新變數。
我知道我可以使用groupby(['user','merchant','date'].apply
并傳遞一個 if-else 陳述句,但我相信這將在一個回圈中完成,我正在嘗試以矢量化的方式來優化我的代碼。
謝謝!
uj5u.com熱心網友回復:
使用慢熊貓選項:
df["new_variable"] = np.where(df.groupby(['user', 'merchant','date'])['amount'].apply(lambda g: g.shift(-1)==-g),2,1)
但是,使用datatable
, 和,shift()
會快得多ifelse()
by()
from datatable import dt, f, by
df = dt.Frame(df)
df[:,
dt.update(new_variable=dt.ifelse(-1*dt.shift(f.amount)==f.amount,2,1)),
by(f.user,f.merchant,f.date)
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/485491.html
標籤:Python r if 语句 熊猫-groupby
上一篇:在Java中獲取產品ID(整數)
下一篇:UncaughtSyntaxError:Invalidleft-handsideinassignment:我不確定是什么導致了這個錯誤?