Bin pandas dataframe by every X rows

TheChymera picture TheChymera · Nov 24, 2013 · Viewed 12.3k times · Source

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!

Answer

Roman Pekar picture Roman Pekar · Nov 24, 2013

In Python 2 use:

>>> df.groupby(df.index / 3).mean()
   col1
0   2.0
1   0.5