Harmonic average over slices of three-dimensional numpy array

Given a three-dimensional array, I want to compute both the arithmetic and harmonic average over two-dimensional slices.

This can easily be done using numpy’s arithmetic average:

import numpy as np
a = np.arange(5*3*3).reshape(5,3,3)

For the harmonic average, I have to slice the three-dimensional array myself. I can do so along the first (0th) axis, for example:

from scipy import stats
b = a.reshape(np.shape(a)[0], -1)

How do I have to reshape/slice my three-dimensional array to compute the average perpendicular to the other axes (that is, average over axes 0 and 2 or over axes 0 and 1)?

To clarify, the corresponding arithmetic averages are simply given by:



You can just stick to numpy and adapt your code to compute harmonic mean as follows-

1/np.mean(1/a, axis=(0,2))
1/np.mean(1/a, axis=(0,1))