Harmonic mean with Python Harmonic mean (using SciPy)

Harmonic mean in Python

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

If you want to get a value like the harmonic mean even if 0 or a negative value appears

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

Harmonic mean with Python Harmonic mean (using SciPy)
[S3] CRUD with S3 using Python [Python]
Using Quaternion with Python ~ numpy-quaternion ~
[Python] Using OpenCV with Python (Basic)
Using OpenCV with Python @Mac
Send using Python with Gmail
Complement python with emacs using company-jedi
[Python] Using OpenCV with Python (Image Filtering)
Using Rstan from Python with PypeR
[Python] Using OpenCV with Python (Image transformation)
[Python] Using OpenCV with Python (Edge Detection)
Notes on using rstrip with python.
When using MeCab with virtualenv python
Precautions when using six with Python 2.5
[AWS] Using ini files with Lambda [Python]
Try mathematical formulas using Σ with python
Behind the flyer: Using Docker with Python
Using Python and MeCab with Azure Databricks
Socket communication using socketserver with python now
Try using Python with Google Cloud Functions
Check stock prices with slackbot using python
Working with OpenStack using the Python SDK
Tips for using python + caffe with TSUBAME
scipy stumbles with pip install on python 2.7.8
I'm using tox and Python 3.3 with Travis-CI
LPC with Scipy
FizzBuzz with Python3
Scraping with Python
Statistics with python
Scraping with Python
Python with Go
Twilio with Python
Integrate with Python
Start using Python
Play with 2016-Python
Try using scipy
AES256 with python
Tested with Python
python starts with ()
with syntax (Python)
ICA with Scipy
Bingo with python
Zundokokiyoshi with python
CORDIC with Scipy
Scraping using Python
Excel with Python
Microcomputer with Python
Cast with python
[Personal memo] julia --Using Python library with julia using PyCall
Debug with VS Code using boost python numpy
I tried using mecab with python2.7, ruby2.3, php7
Using Intel MKL with NumPy / SciPy (November 2019 version)
Recent ranking creation using Qiita API with Python
Find the geometric mean of n! Using Python
Create 3D scatter plot with SciPy + matplotlib (Python)
Portfolio optimization with Python (Markowitz's mean variance model)
What are you using when testing with Python?
Serial communication with Python
Zip, unzip with python
Django 1.11 started with Python3.6
Primality test with Python