Skip to main content
 首页 » 编程设计

python之按连续事件分组的第一个和最后一个之间的 Pandas 差异

2024年09月07日7Leo_wl

我有一个包含开盘/收盘、蜡烛颜色和连续蜡烛数的数据框。

    date open close color  run 
00:01:00  100   102     g    1 
00:02:00  102   104     g    2 
00:03:00  104   106     g    3 
00:04:00  106   105     r    1 
00:05:00  105   101     r    2 
00:06:00  101   102     g    1   
00:06:00  102   103     g    2  

我正在尝试计算运行中第一根蜡烛的开盘价与运行中最后一根蜡烛的收盘价之间差值的绝对值,并将差值应用于每条线。结果看起来像

    date open close color  run  run_length 
00:01:00  100   102     g    1      2        # abs(100 - 102) 
00:02:00  102   104     g    2      4        # abs(100 - 104) 
00:03:00  104   106     g    3      6        # abs(100 - 106) 
00:04:00  106   105     r    1      1        # abs(106 - 105) 
00:05:00  105   101     r    2      5        # abs(106 - 101) 
00:06:00  101   102     g    1      1        # abs(101 - 102) 
00:06:00  102   103     g    2      2        # abs(101 - 103) 

我已经阅读了另外两篇接近但不太了解我正在寻找的解决方案的帖子:

get first and last values in a groupby

Pandas number of consecutive occurrences in previous rows

我正在使用 df.groupby((df['color'] != df['color'].shift()).cumsum()) 按颜色对行进行分组蜡烛(这是我计算颜色和运行计数的方式),我可以使用 .agg(['first', 'last']).stack()< 获取组的第一个和最后一个值 但这不允许我应用原始数据帧的每行差异。

请您参考如下方法:

您在寻找groupby吗?为了更稳健,请按照@Wen 在评论中的建议,使用 cumsum 技巧执行 groupby:

df['run_length'] = df.groupby( 
    df['color'].ne(df['color'].shift()).cumsum() 
).open.transform('first').sub(df.close).abs() 
 
df     
       date  open  close color  run  run_length 
0  00:01:00   100    102     g    1           2 
1  00:02:00   102    104     g    2           4 
2  00:03:00   104    106     g    3           6 
3  00:04:00   106    105     r    1           1 
4  00:05:00   105    101     r    2           5 
5  00:06:00   101    102     g    1           1 
6  00:06:00   102    103     g    2           2