Python : easy way to do geometric mean in python?

2020-05-25 03:55发布

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?

7条回答
疯言疯语
2楼-- · 2020-05-25 04:04

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))
查看更多
倾城 Initia
3楼-- · 2020-05-25 04:10

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

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))
查看更多
一夜七次
4楼-- · 2020-05-25 04:11

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))
查看更多
Evening l夕情丶
5楼-- · 2020-05-25 04:13

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
查看更多
疯言疯语
6楼-- · 2020-05-25 04:27

just do this:

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


print reduce(lambda x, y: x*y, numbers)**(1.0/len(numbers))
查看更多
我只想做你的唯一
7楼-- · 2020-05-25 04:27

You can also calculate the geometrical mean with numpy:

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

result:

1.8171205928321397
查看更多
登录 后发表回答