Here's an approach with ID-based summing/averaging using np.bincount
-
ids = np.arange(len(random_array))//7
out = np.bincount(ids,random_array)/np.bincount(ids)
Sample run -
In [140]: random_array
Out[140]:
array([89, 66, 29, 25, 36, 25, 30, 58, 64, 19, 25, 63, 76, 74, 44, 73, 94,
88, 83, 88, 17, 91, 69, 65, 32, 73, 91, 20, 20, 14, 52, 65, 21, 58,
14, 30, 26, 82, 61, 87, 24, 67, 83, 93, 57, 30, 81, 48, 84, 83, 59,
19, 95, 55, 86, 57, 59, 77, 92, 44, 40, 29, 37, 42, 33, 89, 37, 57,
18, 17, 85, 47, 19, 95, 96, 40, 13, 64, 18, 79, 95, 26, 31, 70, 35,
65, 52, 93, 46, 63, 86, 77, 87, 48, 88, 62, 68, 82, 49, 86])
In [141]: ids = np.arange(len(random_array))//7
In [142]: np.bincount(ids,random_array)/np.bincount(ids)
Out[142]:
array([ 42.85714286, 54.14285714, 69.57142857, 63. ,
34.85714286, 53.85714286, 68. , 64.85714286,
54. , 41.85714286, 56.42857143, 54.71428571,
62.85714286, 73.14285714, 67.5 ])
In [143]: random_array[:7].mean() # Verify output[0]
Out[143]: 42.857142857142854
In [144]: random_array[7:14].mean() # Verify output[1]
Out[144]: 54.142857142857146
In [145]: random_array[98:].mean() # Verify output[-1]
Out[145]: 67.5
For performance, we can replace np.bincount(ids,random_array)
with an alternative one using np.add.reduceat
-
np.add.reduceat(random_array,range(0,len(random_array),7))