![](/img/trans.png)
[英]Keep maximum row in consecutive rows with specific value in column based on another column value
[英]Find maximum and minimum value of five consecutive rows by column
我想獲得按 5 個連續值分組的某些列的最大值和最小值。 例如,我希望連續 5 行的最大值為 a,最小值為 b
a b
0 1 2
1 2 3
2 3 4
3 2 5
4 1 1
5 3 6
6 2 8
7 5 2
8 4 6
9 2 7
我希望有
a b
0 3 1
1 5 2
(其中 3 是 1,2,3,2,1 的最大值,1 是 2,3,4,5,1 的最小值,依此類推)
使用 integer 除法 ( //
) 形成每 5 項分組的索引,然后使用groupby
和agg
:
out = df.groupby(df.index // 5).agg({'a':'max', 'b':'min'})
Output:
>>> out
a b
0 3 1
1 5 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.