Suppose I get a 2d numpy array as an output after each for loop for processing multiple data files.
I intend to stack all 2d numpy arrays every time one loop ends. At the end, I want to get only one 2d numpy array which contains the average of all 2d arrays.
For instance, if I get following arrays after 2 loops,
arr1 = np.arange(1, 10).reshape(3, 3)
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
arr2 = np.arange(10, 19).reshape(3, 3)
array([[10, 11, 12],
[13, 14, 15],
[16, 17, 18]])
I want to get the following array as a final output (outside of the for loop).
array([[5.5, 6.5, 7.5],
[8.5, 9.5, 10.5],
[11.5, 12.5, 13.5]])
I'd appreciate any idea how to (to which direction) stack 2d arrays so that I can obtain the final output with the average.
If there is an ambiguity, I'm happy to provide more backgrounds.
CodePudding user response:
Are you looking for dstack
?
np.dstack([arr1, arr2])
Output:
array([[[ 1, 10],
[ 2, 11],
[ 3, 12]],
[[ 4, 13],
[ 5, 14],
[ 6, 15]],
[[ 7, 16],
[ 8, 17],
[ 9, 18]]])
For the average:
np.dstack([arr1, arr2]).mean(2)
Output:
array([[ 5.5, 6.5, 7.5],
[ 8.5, 9.5, 10.5],
[11.5, 12.5, 13.5]])