0

I have a numpy array like this [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Let's assume I want the average of 3 elements, my target array should then look like this:

[2, 2, 2, 5, 5, 5, 8, 8, 8, 10]

Notice that when there is no triplet available I want to calculate the average over the remaining elements

Is there a neat way to do that with array operations?

DrBwts
  • 3,470
  • 6
  • 38
  • 62
sebko_iic
  • 340
  • 2
  • 16
  • have a look at [np.array_split()](https://docs.scipy.org/doc/numpy/reference/generated/numpy.array_split.html) – DrBwts Oct 20 '19 at 13:56

2 Answers2

0

You could reshape the array to use the mean function, for example:

a = np.arange(1,11)
b = a[:a.size//3*3]
b.shape = (-1,3)
c = np.mean(b, axis=1)
# c == array([2., 5., 8.])

Then reassign the results in the original array:

c.shape = (-1,1)  # i.e. (len(b), 1)
b[:] = c
print(a)
# array([ 2,  2,  2,  5,  5,  5,  8,  8,  8, 10])

Note that this works because b is a sub-view of a. Also the last element is not as you asked the average (I left it untouched), but it'll be easy to fix, with e.g.:

a[9:] = np.mean(a[9:])
Demi-Lune
  • 1,868
  • 2
  • 15
  • 26
0

I have done most of it in a one liner just for fun :D *Notice I'm using sum() to flatten the list.. (that's some weird python trick)

def custom_avg(group: int, arr):
    out = list()
    [out.append(list(np.full( (1, group), np.sum(arr[i:i+group])/ (1 if i + group > len(arr) else group), dtype=int))) for i in range(0, len(arr), group) ]
    return sum(out,[])

Enjoy! good luck.

Ori V Agmon
  • 19
  • 1
  • 2
  • 7
  • that's... some 1-liner... just because you *can* write it in one line. anyway, check the last element of your result, doesn't seem to be correct to me. – FObersteiner Oct 20 '19 at 15:10