Python, Pandas: average every 2 rows together Python, Pandas: average every 2 rows together pandas pandas

Python, Pandas: average every 2 rows together


A fast way to do it:

>>> s = pd.Series(range(10))>>> s0    01    12    23    34    45    56    67    78    89    9>>> ((s + s.shift(-1)) / 2)[::2]0    0.52    2.54    4.56    6.58    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.52    2.54    4.56    6.58    8.5

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