重写groupby,使用ifelse从R到Python进行排列和变异

2024-06-01 20:49:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将我的代码从R重写为Python。我很难重写一些涉及group_byarrangemutate的代码。我在Python中尝试过transformapply,但没有成功。你知道吗

在R中,我的代码如下所示:

S1 = S1 %>% group_by(ID) %>% arrange(Date) %>% mutate(New_Factor = ifelse(r_type == 5, (1+(Price/Last_Price)), Old_Factor/lag(Old_Factor)))

但是,我很难用Python重写这段代码。到目前为止,我得出的结论是:

s1['New_Factor'] = s1.groupby(['ID'],group_keys=False).apply(lambda g: (1+(Price/Last_Price)) if g.type == 5 else (Old_Factor/lag_value))

其中lag_value定义为:

lag_value = s1['Old_Factor'].shift(1)

我得到的错误是:

The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

我还想知道.tranform()是不是更好的方法?请让我知道-因为我可能会做这与我的代码转换相当一点。你知道吗


Tags: 代码idnewbyvaluegrouppriceold