Python,Pandas:平均每2行加在一起 [英] Python, Pandas: average every 2 rows together

查看:544
本文介绍了Python,Pandas:平均每2行加在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个非常基本的问题,但在想:

pretty basic question, but was wondering:

在pandas Dataframe中将每2行平均一次的正确"方法是什么,从而最终只获得一半的行数?

What is the 'proper' way to average every 2 rows together in pandas Dataframe, and thus end up with only half the number of rows?

请注意,这与rolling_mean不同,因为它减少了条目的数量.

Note that this is different than the rolling_mean since it reduces the number of entries.

推荐答案

一种快速的方法:

>>> 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

但是它慢了大约2倍,并且随着大小的增加而变得更糟.

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

这篇关于Python,Pandas:平均每2行加在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆