Select 基于列值及其前 2 行的行

Select a row based on column value and its previous 2 rows

+---+---+---+---+----+
| A | B | C | D | E  |
+---+---+---+---+----+
| 1 | 2 | 3 | 4 | VK |
| 1 | 4 | 6 | 9 | MD |
| 2 | 5 | 7 | 9 | V  |
| 2 | 3 | 5 | 8 | VK |
| 2 | 3 | 7 | 9 | V  |
| 1 | 1 | 1 | 1 | N  |
| 0 | 1 | 6 | 9 | V  |
| 1 | 2 | 5 | 7 | VK |
| 1 | 7 | 8 | 0 | MD |
| 1 | 5 | 7 | 9 | VK |
| 0 | 1 | 6 | 8 | V  |
+---+---+---+---+----+

我想 select 基于列值及其前两行的行。例如,在给定的数据集中(在图片上)我想 select 行基于 'E' 列值 'VK' 和该 selected 行的前两行。所以我们应该得到这样的数据集:

+---+---+---+---+----+
| A | B | C | D | E  |
+---+---+---+---+----+
| 1 | 2 | 3 | 4 | VK |
| 1 | 4 | 6 | 9 | MD |
| 2 | 5 | 7 | 9 | V  |
| 2 | 3 | 5 | 8 | VK |
| 2 | 3 | 7 | 9 | V  |
| 1 | 1 | 1 | 1 | N  |
| 1 | 2 | 5 | 7 | VK |
| 1 | 7 | 8 | 0 | MD |
| 1 | 5 | 7 | 9 | VK |
+---+---+---+---+----+

1st 我们需要过滤数据帧直到最后一个 VK,然后使用 cumsum 创建组密钥,然后执行 groupby head

df=df.loc[:df.E.eq('VK').loc[lambda x : x].index.max()]
df=df.iloc[::-1].groupby(df.E.eq('VK').iloc[::-1].cumsum()).head(3).sort_index()
df
Out[102]: 
   A  B  C  D   E
0  1  2  3  4  VK
1  1  4  6  9  MD
2  2  5  7  9   V
3  2  3  5  8  VK
5  1  1  1  1   N
6  0  1  6  9   V
7  1  2  5  7  VK
8  1  7  8  0  MD
9  1  5  7  9  VK