pandas 每 X 行 Bin 熊猫数据框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20180324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bin pandas dataframe by every X rows
提问by TheChymera
I have a simple dataframe which I would like to bin for every 3 rows.
我有一个简单的数据框,我想每 3 行进行一次分箱。
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 herebut I have no Idea how to port the solution to my current use case.
我已经在这里发布了一个类似的问题,但我不知道如何将解决方案移植到我当前的用例中。
Can you help me out?
你能帮我吗?
Many thanks!
非常感谢!
回答by Roman Pekar
>>> df.groupby(df.index / 3).mean()
col1
0 2.0
1 0.5
回答by ojunk
The answer from Roman Pekar was not working for me. I imagine that this is because of differences between Python2and Python3. This worked for me in Python3:
Roman Pekar 的回答对我不起作用。我想,这是因为之间的差异Python2和Python3。这对我有用Python3:
>>> df.groupby(df.index // 3).mean()
col1
0 2.0
1 0.5
回答by mohaseeb
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":
对于启用了“真正除法”(例如使用from __future__ import division)的Python 2 (2.2+) 用户, 您需要使用“//”运算符来表示“地板除法”:
df.groupby(df.index // 3).mean()

