Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rolling non-overlapping window in pandas

Tags:

python

pandas

My dataframe looks like:

       c1   
    0  10  
    1  11  
    2  12
    3  13
    4  14
    5  15
    6  16
    7  17

I want to find the minimum for every 3 rows. which looks like:

       c1  min 
    0  10  10
    1  11  10
    2  12  10
    3  13  13
    4  14  13
    5  15  13
    6  16  16
    7  17  16

and the number of rows might not be divisible by 3. I can't achieve it with rolling function.

like image 667
Bubblethan Avatar asked Jan 26 '23 13:01

Bubblethan


2 Answers

If there is default index values use integer division by 3 and pass to GroupBy.transform with min:

df['min'] = df['c1'].groupby(df.index // 3).transform('min')

Or if any index generate helper np.arange:

df['min'] = df['c1'].groupby(np.arange(len(df)) // 3).transform('min')

print (df)
   c1  min
0  10   10
1  11   10
2  12   10
3  13   13
4  14   13
5  15   13
6  16   16
7  17   16
like image 134
jezrael Avatar answered Jan 28 '23 01:01

jezrael


You can also do this:

>>> df['min'] = df['c1'][::3]
>>> df.ffill().astype(int)

   c1  min
0  10   10
1  11   10
2  12   10
3  13   13
4  14   13
5  15   13
6  16   16
7  17   16
like image 21
Sayandip Dutta Avatar answered Jan 28 '23 03:01

Sayandip Dutta