Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bin pandas dataframe by every X rows

I have a simple dataframe which I would like to bin for every 3 rows.

It looks like this:

    col1
0      2
1      1
2      3
3      1
4      0

and I would like to turn it into this:

    col1
0      2
1    0.5

I have already posted a similar question here but I have no Idea how to port the solution to my current use case.

Can you help me out?

Many thanks!

like image 472
TheChymera Avatar asked Nov 24 '13 20:11

TheChymera


3 Answers

In Python 2 use:

>>> df.groupby(df.index / 3).mean()
   col1
0   2.0
1   0.5
like image 194
Roman Pekar Avatar answered Oct 09 '22 23:10

Roman Pekar


The answer from Roman Pekar was not working for me. I imagine that this is because of differences between Python2 and Python3. This worked for me in Python3:

>>> df.groupby(df.index // 3).mean()
   col1
0   2.0
1   0.5
like image 25
ojunk Avatar answered Oct 09 '22 23:10

ojunk


For Python 2 (2.2+) users, who have "true division" enabled (e.g. by using from __future__ import division), you need to use the "//" operator for "floor division":

df.groupby(df.index // 3).mean()
like image 37
mohaseeb Avatar answered Oct 09 '22 23:10

mohaseeb