Both numpy.count_nonzero and numpy.nanmean take in axis parameter to specify along which axis it should calculate these values, so if you pass axis = 2
to each (2 being the 3rd axis, i.e.(0,1,2)), you don't need the loops.
samples = np.count_nonzero(~np.isnan(time_series), axis = 2)
means = np.nanmean(time_series, axis = 2)
Will give the same results as your double loop.
Checked both with %%timeit
on my jupyter notebook and using numpy axis parameter is indeed at least 5 times faster than the loops (this will depend on the complexity of your arrays, but from my few attempts the gain in performance time gets better with increased complexity).
Results:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…