python - pandas 列的条件累积和

标签 python pandas dataframe

我有以下数据框:

indicator = ["buy"] + ["hold"]*3 + ["sell"] + ["hold"]*4 + ["buy"] + ["hold"] * 2
values = np.random.randn(len(indicator)) / 100
df = pd.DataFrame({"indicator": indicator, "values": values})
df

OUTPUT
    indicator   values
0   buy      0.001810
1   hold     0.011779
2   hold    -0.003350
3   hold    0.010311
4   sell    -0.010846
5   hold    -0.013635
6   hold    0.003794
7   hold    -0.003792
8   hold    0.006421
9   buy    -0.019779
10  hold    0.007123
11  hold    0.025983

我想根据列indicator的以下逻辑来累积列:

  • 买入累积所有行时,直到卖出
  • 当所有行的卖出累计时,直到买入

此外,我想知道买入卖出周期的长度。

预期的输出是这样的:

    indicator   values  period  Cumsum
0   buy     0.004730    1   0.004730
1   hold    -0.006814   1   -0.002084
2   hold    0.002424    1   0.000340
3   hold    -0.017007   1   -0.016667
4   sell    0.007531    2   0.007531
5   hold    -0.015347   2   -0.007816
6   hold    0.000051    2   -0.007765
7   hold    -0.001202   2   -0.008967
8   hold    -0.008070   2   -0.017037
9   buy     0.028718    3   0.028718
10  hold    -0.005978   3   0.022740
11  hold    0.004725    3   0.027465

我该如何进行这个条件累积。一旦我有了period列,我就可以执行.groupby("period")。但是 pandas 生成此列的方式是什么?

最佳答案

您可以首先对指标未持有进行求和:

df['period'] = df['indicator'].ne('hold').cumsum()
df['Cumsum'] = df.groupby('period')['values'].cumsum()

您可以通过以下方式获取尺寸:

df.groupby('period').size()

输出:

   indicator    values  period    Cumsum
0        buy  0.001810       1  0.001810
1       hold  0.011779       1  0.013589
2       hold -0.003350       1  0.010239
3       hold  0.010311       1  0.020550
4       sell -0.010846       2 -0.010846
5       hold -0.013635       2 -0.024481
6       hold  0.003794       2 -0.020687
7       hold -0.003792       2 -0.024479
8       hold  0.006421       2 -0.018058
9        buy -0.019779       3 -0.019779
10      hold  0.007123       3 -0.012656
11      hold  0.025983       3  0.013327

关于python - pandas 列的条件累积和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73571101/

相关文章:

python - 在 Python 中将数据写入 UART 并从 C 中读取它们

python - GCP/Py : determine when compute engine instance is actually ready to be used (not "RUNNING")

python - 如何使用 pandas 处理多索引数据

python - 应用 pandas group 函数保留其他列

python - 如何使用 Python Pandas 合并多个 CSV 文件

reshape 调查数据以获取 R 中的响应计数

python - pydantic @validate_arguments 非内置类型(如 pandas DataFrame)的最佳实践

Python:发送电子邮件时,始终在子句中阻止:smtpserver = smtplib.SMTP ("smtp.gmail.com",587)

python - 将 pandas 列定位或移动到特定的列索引

python - 使用 Streaming API 避免 420?