Harmonic Mean in Python

				
					# Dataset
runners = [4, 3, 6, 8, 10, 11, 5]
				
			

Example 1 Manual Calc

				
					n = len(runners)
				
			
				
					# Calculate the sum of reciprocals
reciprocal_sum = sum(1/x for x in runners)
				
			
				
					# Calculate harmonic mean
harmonic_mean_manual = n / reciprocal_sum
				
			
				
					harmonic_mean_manual
				
			

Example 2 statistics

				
					import statistics as stats
				
			
				
					# Calculate harmonic mean
data = runners
harmonic_mean_stats = stats.harmonic_mean(runners)
				
			
				
					print(harmonic_mean_stats)
				
			
				
					df.loc[idx]
				
			
				
					df.loc[idx]
				
			

Example 3 scipy

				
					from scipy.stats import hmean
harmonic_mean_scipy = hmean(data)
				
			
				
					print(harmonic_mean_scipy)
				
			

Ryan is a Data Scientist at a fintech company, where he focuses on fraud prevention in underwriting and risk. Before that, he worked as a Data Analyst at a tax software company. He holds a degree in Electrical Engineering from UCF.

Leave a Reply

Your email address will not be published. Required fields are marked *