简体   繁体   English

Pandas Reverse Group来自 Cumprod

[英]Pandas Reverse Groupby Cumprod

I am trying to set a column to be the reverse cumprod of a series after grouping on another series in a data frame.在对数据框中的另一个系列进行分组后,我试图将一列设置为系列的反向 cumprod。

Attempt 1:
temp_data["factor_price"] = temp_data["factor_price"].groupby("stock_key").cumprod()[::-1]
Attempt 2:
temp_data["factor_price"] = temp_data.groupby("stock_key")["factor_price"].cumprod()[::-1]
Attempt 3: 
temp_data["factor_price"] = temp_data.groupby("stock_key")["factor_price"][::-1].cumprod()
input: temp_data = pd.DataFrame([x, x, x, y, y, y], [1, 2, 3, 0, 1, 2], columns=[
"stock_key", "factor_price"])

Output: Pd.Series(6, 6, 3, 0, 2, 2)

I have been researching a lot, and I think I could do it if I looped through the groups, but this is an exceptionally large data set and I would like to keep the code as simple as possible.我一直在研究很多,我想如果我循环遍历这些组我可以做到,但这是一个非常大的数据集,我希望代码尽可能简单。 Is there a chance this could be a one liner?这有没有可能是一个班轮?

Thanks!谢谢!

so I needed to apply a custom function that did the cumprod, and then convert everything to a list because of the incompatible indices with the original data frame.所以我需要应用一个自定义的 function 来完成 cumprod,然后将所有内容转换为列表,因为与原始数据帧的索引不兼容。

temp_data["factor_price"] = temp_data.groupby("stock_key")["factor_price"].apply(lambda x: 
x[::-1].cumprod()[::-1]).to_list()

You can do it without a lambda function as -您可以在没有lambda function 的情况下执行此操作 -

temp_data[::-1].groupby('stock_key')['factor_price'].cumprod()[::-1]

The first [::-1] reverses the row order of the dataset for expected cumprod() and the second one reverses it back to get back the original order of indices.第一个[::-1]反转预期cumprod()的数据集的行顺序,第二个反转它以恢复索引的原始顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM