Bin pandas dataframe by every X rows

前端 未结 3 1093
余生分开走
余生分开走 2020-11-30 07:43

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


        
相关标签:
3条回答
  • 2020-11-30 08:11

    In Python 2 use:

    >>> df.groupby(df.index / 3).mean()
       col1
    0   2.0
    1   0.5
    
    0 讨论(0)
  • 2020-11-30 08:18

    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
    
    0 讨论(0)
  • 2020-11-30 08:28

    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()
    
    0 讨论(0)
提交回复
热议问题