2964502
2964502

Reputation: 4479

array manipulation in numpy

How to obtain new array (new) from original array (x) by calculating mean as follows:

new = [[mean(1,3), mean(1,3), mean(1,3), mean(1,3), mean(1,3)],[mean(2,4),mean(2,4),mean(2,4),mean(2,4),mean(2,4)]]


import numpy as np

arr1 = np.array([[1,1,1,1,1],[2,2,2,2,2]])
arr2 = np.array([[3,3,3,3,3],[4,4,4,4,4]])
my_array = np.array([arr1,arr2])

for x in my_array:    
    new = np.mean(x,axis=1)
    print (new)

IMPORTANT: The arr1, arr2, and my_array are not really available as inputs, what is available is only x. So, the real data to be manipulated are in the form of for loop given by x as shown above.

Upvotes: 1

Views: 192

Answers (1)

rroowwllaanndd
rroowwllaanndd

Reputation: 3958

Given my_array as defined above

>>> my_array
array([[[1, 1, 1, 1, 1],
        [2, 2, 2, 2, 2]],

       [[3, 3, 3, 3, 3],
        [4, 4, 4, 4, 4]]])

You simply need to take the mean over the first axis as follows:

>>> my_array.mean(axis=0)
array([[ 2.,  2.,  2.,  2.,  2.],
       [ 3.,  3.,  3.,  3.,  3.]])

If it must be iterative for subsequent x you could do the following:

sums = 0
counter = 0
for x in my_array:
  sums += x
  counter += 1
new = sums / counter

Or, if you can store the data:

data = []
for x in my_array:
  data.append(x)
new = np.dstack(data).mean(axis=2)

Upvotes: 3

Related Questions