Python, Pandas: average every 2 rows together

Deadly 提交于 2019-12-05 10:37:49

A fast way to do it:

>>> s = pd.Series(range(10))
>>> s
0    0
1    1
2    2
3    3
4    4
5    5
6    6
7    7
8    8
9    9
>>> ((s + s.shift(-1)) / 2)[::2]
0    0.5
2    2.5
4    4.5
6    6.5
8    8.5

The "proper way" I guess would be something like:

>> a = s.index.values
>>> idx = np.array([a, a]).T.flatten()[:len(a)]
>>> idx
[0 0 1 1 2 2 3 3 4 4]
>>> s.groupby(idx).mean()
0    0.5
2    2.5
4    4.5
6    6.5
8    8.5

But it is ~2x slower and gets worse with increasing size.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!