Use Python's SciPy to find the harmonic mean. Install SciPy first.
If all the calculation targets are not values greater than 0 (positive real numbers), an exception will be thrown. Negative numbers reduce the denominator and result in a large harmonic mean. For example, if the harmonic mean of 3, -3,4 is calculated according to the formula, it will be 12. Such values cannot be used.
harmonic_mean1.py
from scipy import stats
# 1, 2,Harmonic mean of 4 ⇒ 1.71428571429
print stats.hmean([1, 2, 4])
# 1, 0.5, 2.0,Harmonic mean of 10 ⇒ 1.11111111111
print stats.hmean([1, 0.5, 2.0, 10])
#After that, an example of trying a negative value
# 3,-3,Harmonic mean of 4 ⇒ Value Error: Harmonic mean only defined if all elements greater than zero
print stats.hmean([3, -3, 4])
#When calculated according to the formula of harmonic mean ⇒ 12 values increased!?No, it is an invalid value.
print(3 / ((1 / 3.0) + (1 / -3.0) + (1 / 4.0)))
harmonic_mean2.py
from scipy import stats
HM_OFFSET = 0.0001
def custom_hmean(values_list):
u"""Wrapper with exceptions to the harmonic mean function."""
#If all the values to be calculated are None, the harmonic mean is set to None.
if values_list[0] is None and\
values_list == [values_list[0]] * len(values_list):
return None
#If all the calculated values are 0 or less, the harmonic mean is set to 0.
if max(values_list) <= 0:
return 0
#If the value to be calculated is None, it is considered that there is no data, and if it is 0 or less, HM_Set to the value of OFFSET
return stats.hmean(
[v if v > 0 else HM_OFFSET for v in values_list if v is not None])
print custom_hmean([3, 0, 4]) # 0.000299982501021
print custom_hmean([3, None, 4]) # 3.42857142857
print custom_hmean([0, -1, -2, -3]) # 0
print custom_hmean([0, -1, -2, 1]) # 0.000133328889037
print custom_hmean([0, 0, 1, 0]) # 0.000133328889037
print custom_hmean([None, None, 1, None]) # 1.0
print custom_hmean([None, None, None, None]) # None
print custom_hmean([0, 0, 0, 0]) # 0
Details of scipy.stats.hmean English Refer to Wikipedia for the formula of the harmonic mean ⇒ Harmonic mean Is the reciprocal of the arithmetic mean of the reciprocal
Recommended Posts