我想groupby
“ts_code”并根据每个组的最后 N 行计算 max 之后另一列的一列最大值和最小值之间的百分比。具体来说,
df
ts_code high low
0 A 20 10
1 A 30 5
2 A 40 20
3 A 50 10
4 A 20 30
5 B 20 10
6 B 30 5
7 B 40 20
8 B 50 10
9 B 20 30
目标
以下是我的预期结果
ts_code high low l3_high_low_pct_chg l4_high_low_pct_chg
0 A 20 10 NA NA
1 A 30 5 NA NA
2 A 40 20 0.5 NA
3 A 50 10 0.8 0.8
4 A 20 30 0.4 0.4
5 B 50 10 NA NA
6 B 30 5 NA NA
7 B 40 20 0.6 NA
8 B 10 10 0.75 0.9
9 B 20 30 0.75 0.75
l3_high_low_pct_chg
= 1-(low
峰值后列的最小值)/(列的最大值high
),在每组和每行的最后 3 行。
尝试和问题
df['l3_highest']=df.groupby('ts_code')['high'].transform(lambda x: x.rolling(3).max())
df['l3_lowest']=df.groupby('ts_code')['low'].transform(lambda x: x.rolling(3).min())
df['l3_high_low_pct_chg']=1-df['l3_lowest']/df['l3_highest']
但它失败了,因此对于第二行,l3_lowest
将是 5 而不是 20。我不知道如何计算峰值后的百分比。