问题
I notice that
In [30]: np.mean([1, 2, 3])
Out[30]: 2.0
In [31]: np.average([1, 2, 3])
Out[31]: 2.0
However, there should be some differences, since after all they are two different functions.
What are the differences between them?
回答1:
np.average takes an optional weight parameter. If it is not supplied they are equivalent. Take a look at the source code: Mean, Average
np.mean:
try:
mean = a.mean
except AttributeError:
return _wrapit(a, 'mean', axis, dtype, out)
return mean(axis, dtype, out)
np.average:
...
if weights is None :
avg = a.mean(axis)
scl = avg.dtype.type(a.size/avg.size)
else:
#code that does weighted mean here
if returned: #returned is another optional argument
scl = np.multiply(avg, 0) + scl
return avg, scl
else:
return avg
...
回答2:
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.
回答3:
In some version of numpy there is another imporant difference that you must be aware:
average
do not take in account masks, so compute the average over the whole set of data.
mean
takes in account masks, so compute the mean only over unmasked values.
g = [1,2,3,55,66,77]
f = np.ma.masked_greater(g,5)
np.average(f)
Out: 34.0
np.mean(f)
Out: 2.0
回答4:
In your invocation, the two functions are the same.
average
can compute a weighted average though.
Doc links: mean and average
来源:https://stackoverflow.com/questions/20054243/np-mean-vs-np-average-in-python-numpy