Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Average values in two Numpy arrays

Given two ndarrays

old_set = [[0, 1], [4, 5]] new_set = [[2, 7], [0, 1]] 

I'm looking to get the mean of the respective values between the two arrays so that the data ends up something like:

end_data = [[1, 4], [2, 3]] 

basically it would apply something like

for i in len(old_set):     end_data[i] = (old_set[i]+new_set[i])/2 

But I'm unsure what syntax to use.. Thanks for the help in advance!

like image 899
Forde Avatar asked Aug 27 '13 09:08

Forde


People also ask

How do you find the average of a NumPy array?

The numpy. mean() function returns the arithmetic mean of elements in the array. If the axis is mentioned, it is calculated along it.

How do you find the average of a two dimensional array in Python?

To calculate the average separately for each column of the 2D array, use the function call np. average(matrix, axis=0) setting the axis argument to 0. The resulting array has three average values, one per column of the input matrix .

What is the difference between NP mean and NP average?

np. mean always computes an arithmetic mean, and has some additional options for input and output (e.g. what datatypes to use, where to place the result). np. average can compute a weighted average if the weights parameter is supplied.


1 Answers

You can create a 3D array containing your 2D arrays to be averaged, then average along axis=0 using np.mean or np.average (the latter allows for weighted averages):

np.mean( np.array([ old_set, new_set ]), axis=0 ) 

This averaging scheme can be applied to any (n)-dimensional array, because the created (n+1)-dimensional array will always contain the original arrays to be averaged along its axis=0.

like image 167
Saullo G. P. Castro Avatar answered Sep 21 '22 00:09

Saullo G. P. Castro