Reputation: 661
What I'm trying to do is to reduce the "resolution" of 1D data by finding the mean of every distinct pair of elements and setting the values to that mean. For example:
[ 1, 2, 3, 4 ]
should become:
[ 1.5, 1.5, 3.5, 3.5 ]
If the number of elements is odd, then the last one stays as it is, or is removed/ignored. Is there an easy way to do this?
Perhaps it would be easier to first get [ 1.5, 3.5 ]
and then duplicate each element — I'm not sure.
Eventually I would like to keep doing this recursively (or iteratively for every pair, then every four, then every eight, then every 2^i) such that the resolution becomes lower and lower until it's just a grand mean.
Upvotes: 0
Views: 936
Reputation: 53029
You could use reshape like
a = np.arange(1,15)
# groups of four in this example
k = 4
result = np.empty(a.shape)
# arrange the elements in as many full (4 item) rows as possible
rect = k * (len(a) // k)
resview = np.reshape(result[:rect], (-1, k))
# perform mean along rows without collapsing them
resview[...] = np.mean(np.reshape(a[:rect], (-1, k)), axis=-1, keepdims=True)
if len(a) > rect:
# handle the last, incomplete (<4 items) row
result[rect:] = a[rect:].mean()
print(result)
[ 2.5 2.5 2.5 2.5 6.5 6.5 6.5 6.5 10.5 10.5 10.5 10.5 13.5 13.5]
Upvotes: 3