'Python : easy way to do geometric mean in python?
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?
Solution 1:[1]
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 import gmean
>>> gmean([1.0, 0.00001, 10000000000.])
46.415888336127786
Compatible with both Python 2 and 3.*
Solution 2:[2]
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
Solution 3:[3]
just do this:
numbers = [1, 3, 5, 7, 10]
print reduce(lambda x, y: x*y, numbers)**(1.0/len(numbers))
Solution 4:[4]
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))
Solution 5:[5]
you can use pow function, as follows :
def p(*args):
k=1
for i in args:
k*=i
return pow(k, 1/len(args))]
>>> p(2,3)
2.449489742783178
Solution 6:[6]
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
Solution 7:[7]
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))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | |
| Solution 4 | rmmh |
| Solution 5 | Asclepius |
| Solution 6 | gil.fernandes |
| Solution 7 | Asclepius |
