Python : easy way to do geometric mean in python?

冷暖自知 提交于 2019-12-20 17:34:12

问题


I wonder is there any easy way to do geometric mean using python but without using python package. If there is not, is there any simple package to do geometric mean?


回答1:


The formula of the gemetric mean is:

So you can easily write an algorithm like:

import numpy as np

def geo_mean(iterable):
    a = np.array(iterable)
    return a.prod()**(1.0/len(a))

You do not have to use numpy for that, but it tends to perform operations on arrays faster than Python (since there is less "overhead" with casting).

In case the chances of overflow are high, you can map the numbers to a log domain first, calculate the sum of these logs, then multiply by 1/n and finally calculate the exponent, like:

import numpy as np

def geo_mean_overflow(iterable):
    a = np.log(iterable)
    return np.exp(a.sum()/len(a))



回答2:


In case someone is looking here for a library implementation, there is gmean() in scipy, possibly faster and numerically more stable than a custom implementation:

>>> from scipy.stats.mstats import gmean
>>> gmean([1.0, 0.00001, 10000000000.])
46.415888336127786



回答3:


Starting Python 3.8, the standard library comes with the geometric_mean function as part of the statistics module:

from statistics import geometric_mean

geometric_mean([1.0, 0.00001, 10000000000.]) // 46.415888336127786



回答4:


just do this:

numbers = [1, 3, 5, 7, 10]


print reduce(lambda x, y: x*y, numbers)**(1.0/len(numbers))



回答5:


Here's an overflow-resistant version in pure Python, basically the same as the accepted answer.

import math

def geomean(xs):
    return math.exp(math.fsum(math.log(x) for x in xs) / len(xs))



回答6:


Geometric mean

import pandas as pd
geomean=Variable.product()**(1/len(Variable))
print(geomean)

Geometric mean with Scipy

from scipy import stats
print(stats.gmean(Variable))


来源:https://stackoverflow.com/questions/43099542/python-easy-way-to-do-geometric-mean-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!