Apply function to groups of k pandas series elements

I have a pandas series:

0     1
1     5
2    20
3    -1

Suppose I want to apply mean()to each of the two elements, so I get something like this:

0    3.0
1    9.5

Is there an elegant way to do this?

+4
source share
3 answers

You can use divide by :groupby indexk=2

k = 2
print (s.index // k)
Int64Index([0, 0, 1, 1], dtype='int64')

print (s.groupby([s.index // k]).mean())
   name
0   3.0
1   9.5
+3
source

If you use it in a large series and many times, you will need to consider a quick approach. This solution uses all the numpy features and will be fast.

Use reshapeand create newpd.Series

consider pd.Series s

s = pd.Series([1, 5, 20, -1])

generalized function

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

demonstration

mean_k(s, 2)

0    3.0
1    9.5
dtype: float64

mean_k(s, 3)

0    8.666667
1   -1.000000
dtype: float64
+1

:

(s.iloc[::2].values + s.iloc[1::2])/2

, reset , 0, 1 , :

((s.iloc[::2].values + s.iloc[1::2])/2).reset_index(drop=True)
+1

Source: https://habr.com/ru/post/1656176/


All Articles