Python:在python中做几何平均值的简单方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43099542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:30:56  来源:igfitidea点击:

Python : easy way to do geometric mean in python?

pythonmathstatisticsgeometric-mean

提问by Marcin Wojnarski

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?

我想知道有没有什么简单的方法可以使用 python 但不使用 python 包来做几何平均。如果没有,是否有任何简单的包来做几何平均?

回答by Willem Van Onsem

The formula of the gemetric mean is:

几何均值的公式为:

geometrical mean

几何平均数

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).

您不必为此使用 numpy,但它倾向于比 Python 更快地对数组执行操作(因为转换的“开销”较少)。

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

如果溢出的可能性很高,您可以先将数字映射到对域,计算这些对数的总和,然后乘以 1/n,最后计算指数,例如:

import numpy as np

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

回答by Marcin Wojnarski

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:

如果有人在这里寻找库实现,scipy 中gmean(),可能比自定义实现更快且数值更稳定:

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

回答by Xavier Guihot

Starting Python 3.8, the standard library comes with the geometric_meanfunction as part of the statisticsmodule:

开始Python 3.8,标准库附带该geometric_mean功能作为statistics模块的一部分:

from statistics import geometric_mean

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

回答by rmmh

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

这是纯Python中的防溢出版本,与接受的答案基本相同。

import math

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

回答by Liam

just do this:

只需这样做:

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


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

回答by user12295593

Geometric mean

几何平均数

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

Geometric mean with Scipy

Scipy 的几何平均值

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

回答by gil.fernandes

You can also calculate the geometrical mean with numpy:

您还可以使用 numpy 计算几何平均值:

import numpy as np
np.exp(np.mean(np.log([1, 2, 3])))

result:

结果:

1.8171205928321397