How do I change values in my subarrays into the avarage of those values?

63 Views Asked by At

I have an array:

> a

array([[1, 2, 3], [2, 3, 4], [3, 4, 5]])

I want to change those values to the avarage of those values, so the output will be:

> a

array([[2, 2, 2], [3, 3, 3], [4, 4, 4]])

Is there a fast way to do this without using a for loop?

3

There are 3 best solutions below

0
Suraj Shourie On BEST ANSWER

If you are able to use numpy module the broadcasting functions are useful for this (Though they do this by highly optimized loops as well).

a.mean(axis=1) gets the row mean and np.broadcast_to broadcasts the result to the desired shape. .T just returns transpose of the result

import numpy as np
a = np.array([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
np.broadcast_to(a.mean(axis=1), a.shape).T

Output:

array([[2., 2., 2.],
       [3., 3., 3.],
       [4., 4., 4.]])
0
Reilas On

"... Is there a fast way to do this without using a for loop? ..."

You can use a list comprehension.
Note, I'm using the int function here, since your provided data was non-fractional.

a = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
a = [([int(sum(x) / len(x))] * 3) for x in a]

Output

[[2, 2, 2], [3, 3, 3], [4, 4, 4]]
0
PaulS On

Another possible solution:

n = a.shape[1]
np.repeat(a.mean(axis=1), n).reshape(-1, n)

Output:

array([[2., 2., 2.],
       [3., 3., 3.],
       [4., 4., 4.]])