apply function on groups of k elements of a pandas Series
<p>I have a pandas Series:</p>

<pre><code>0     1
1     5
2    20
3    -1
</code></pre>

<p>Lets say I want to apply <code>mean()</code> on every two elements, so I get something like this:</p>

<pre><code>0    3.0
1    9.5
</code></pre>

<p>Is there an elegant way to do this?</p>

<p>If you are using this over large series and many times, you'll want to consider a fast approach.  This solution uses all numpy functions and will be fast.</p>

<p>Use <code>reshape</code> and construct new <code>pd.Series</code></p>

<p>consider the <code>pd.Series</code> <code>s</code></p>

<pre><code>s = pd.Series([1, 5, 20, -1])
</code></pre>

<hr>

<p><strong><em>generalized function</em></strong></p>

<pre><code>def mean_k(s, k):
    pad = (k - s.shape[0] % k) % k
    nan = np.repeat(np.nan, pad)
    val = np.concatenate([s.values, nan])
    return pd.Series(np.nanmean(val.reshape(-1, k), axis=1))
</code></pre>

<p><strong><em>demonstration</em></strong></p>

<pre><code>mean_k(s, 2)

0    3.0
1    9.5
dtype: float64
</code></pre>

<hr>

<pre><code>mean_k(s, 3)

0    8.666667
1   -1.000000
dtype: float64
</code></pre>

python pandas group-by mean series