Harmonic Mean Function in python pandas is used to calculate the harmonic mean of a given set of numbers, Harmonic mean of a data frame, Harmonic mean of column and Harmonic mean of rows. let’s see an example of each we need to use the package name “stats” from scipy in calculation of harmonic mean. In this tutorial we will learn,
- How to find the harmonic mean of a given set of numbers
- How to find harmonic mean of a dataframe
- How to find the harmonic mean of a column in dataframe
- How to find row wise harmonic mean of a dataframe
Harmonic Mean Function in Python
Simple harmonic mean function is shown below
# calculate harmonic mean from scipy import stats print(stats.hmean([1,9,5,6,6,7])) print(stats.hmean([4,11,15,16,5,7]))
output:
3.35701598579
7.38068295281
7.38068295281
Harmonic Mean of a dataframe:
Create dataframe
import pandas as pd import numpy as np from scipy import stats #Create a DataFrame d = { 'Name':['Alisa','Bobby','Cathrine','Madonna','Rocky','Sebastian','Jaqluine', 'Rahul','David','Andrew','Ajay','Teresa'], 'Score1':[62,47,55,74,31,77,85,63,42,32,71,57], 'Score2':[89,87,67,55,47,72,76,79,44,92,99,69]} df = pd.DataFrame(d) df
So the resultant dataframe will be
Harmonic Mean of the column in dataframe:
# Harmonic Mean of the column in dataframe from scipy import stats scipy.stats.hmean(df.iloc[:,1:3],axis=0)
axis=0 argument calculates the column wise harmonic mean of the dataframe so the result will be
array([ 52.4769906 , 68.56766396])
Row wise harmonic Mean of the dataframe:
# Row wise harmonic mean of the dataframe from scipy import stats scipy.stats.hmean(df.iloc[:,1:3],axis=1)
axis=1 argument calculates the row wise harmonic mean of the dataframe so the result will be
Calculate the harmonic mean of the specific Column:
# harmonic mean of the specific column from scipy import stats scipy.stats.hmean(df.loc[:,"Score1"])
the above code calculates the harmonic mean of the “Score1” column so the result will be
52.476990604079674