Vous pouvez utiliser l'identité (je ne trouve dans le german Wikipedia mais il y a probablement d'autres sources aussi bien):
Cette identité peut être construit en utilisant les « règles de logarithme » sur la normale définition de la moyenne géométrique:
la base a
peut être choisi arbitarly, de sorte que vous pouvez utiliser np.log
(et np.exp
en fonctionnement inverse):
import numpy as np
def nangmean(arr, axis=None):
arr = np.asarray(arr)
inverse_valids = 1./np.sum(~np.isnan(arr), axis=axis) # could be a problem for all-nan-axis
rhs = inverse_valids * np.nansum(np.log(arr), axis=axis)
return np.exp(rhs)
Et il semble au travail:
>>> l = [[1, 2, 3], [1, np.nan, 3], [np.nan, 2, np.nan]]
>>> nangmean(l)
1.8171205928321397
>>> nangmean(l, axis=1)
array([ 1.81712059, 1.73205081, 2. ])
>>> nangmean(l, axis=0)
array([ 1., 2., 3.])
Dans NumPy 1.10 également np.nanprod
a été ajouté, vous pouvez également utiliser la définition normale:
import numpy as np
def nangmean(arr, axis=None):
arr = np.asarray(arr)
valids = np.sum(~np.isnan(arr), axis=axis)
prod = np.nanprod(arr, axis=axis)
return np.power(prod, 1./valids)
https://stackoverflow.com/questions/19852586/get-mean-value-avoiding-nan-using-numpy-in-python ou htt ps: //stackoverflow.com/questions/5480694/numpy-calculate-averages-with-nans-removed pour une version plus efficace et légèrement plus longue, mais remplacez 'mean' par' geomean' – Ryan