我是按Pandas 分组计算pct_change的,但从每组的第一个元素开始算起.因此,我使用cumprod().我已经有了一个可以工作的代码,但它有点难看.我怎样才能把pct_change()cumprod()放在一起呢?

My code:

import pandas as pd
import numpy as np

data = [[1, 10], [2, 17], [3, 15],[4, 11], [5, 17], [6, 15]]
df = pd.DataFrame(data, columns=["id", "open"])

#normal
df['Normal'] =df['open'].pct_change().fillna(0).add(1).cumprod().sub(1).mul(100).round(2)


#groupby
df["Group_of_3"] = df.groupby(np.arange(len(df)) // 3 )["open"].pct_change().fillna(0).add(1)
df["Group_of_3"] = df.groupby(np.arange(len(df)) // 3 )["Group_of_3"].cumprod().sub(1).mul(100).round(2)


print(df)

output

   id  open  Normal  Group_of_3
0   1    10     0.0        0.00
1   2    17    70.0       70.00
2   3    15    50.0       50.00
3   4    11    10.0        0.00
4   5    17    70.0       54.55
5   6    15    50.0       36.36

推荐答案

当然,您可以使用自定义函数简化重复的代码,并避免重复的groupby.使用groupby.tranform作为第二列:

def pct_cumprod(s):
    return s.pct_change().fillna(0).add(1).cumprod().sub(1).mul(100).round(2)

df['Normal'] = pct_cumprod(df['open'])

df['Group_of_3'] = (df.groupby(np.arange(len(df)) // 3)['open']
                      .transform(pct_cumprod)
                    )

如果您只需要Group_of_3列:

df['Group_of_3'] = (df.groupby(np.arange(len(df)) // 3)['open']
                      .transform(lambda g: g.pct_change().fillna(0).add(1)
                                            .cumprod().sub(1).mul(100)
                                            .round(2))
                   )

输出:

   id  open  Normal  Group_of_3
0   1    10     0.0        0.00
1   2    17    70.0       70.00
2   3    15    50.0       50.00
3   4    11    10.0        0.00
4   5    17    70.0       54.55
5   6    15    50.0       36.36

Python相关问答推荐

如何将ctyles.POINTER(ctyles.c_float)转换为int?

max_of_three使用First_select、second_select、

如何在python xsModel库中定义一个可选[December]字段,以产生受约束的SON模式

Telethon加入私有频道

将pandas Dataframe转换为3D numpy矩阵

当从Docker的--env-file参数读取Python中的环境变量时,每个\n都会添加一个\'.如何没有额外的?

如何将多进程池声明为变量并将其导入到另一个Python文件

在Python argparse包中添加formatter_class MetavarTypeHelpFormatter时, - help不再工作""""

如何让这个星型模式在Python中只使用一个for循环?

删除marplotlib条形图上的底边

基于另一列的GROUP-BY聚合将列添加到Polars LazyFrame

如何编辑此代码,使其从多个EXCEL文件的特定工作表中提取数据以显示在单独的文件中

Python:从目录内的文件导入目录

Pandas:将值从一列移动到适当的列

替换包含Python DataFrame中的值的<;

对当前的鼹鼠进行编码,并且我的按键获得了注册

了解如何让库认识到我具有所需的依赖项

如何在微调Whisper模型时更改数据集?

`Convert_time_zone`函数用于根据为极点中的每一行指定的时区检索值

从`end_date`回溯,如何计算以极为单位的滚动统计量?