Geometric Mean in Python

				
					import numpy as np
from scipy.stats import gmean
				
			

Example 1 Manual

				
					data = [4, 7, 3, 8, 2, 1, 5]
				
			
				
					n = len(data)
				
			
				
					product = 1
				
			
				
					for x in data:
        product *= x
				
			
				
					geometric_mean = product ** (1/n)
				
			
				
					print(geometric_mean)
				
			

Example 2 Numpy

				
					product_np = np.prod(data)
				
			
				
					result_numpy = np.power(product_np, 1/n)
				
			
				
					print(result_numpy)
				
			

Example 3 Scipy

				
					result_scipy = gmean(data)
				
			
				
					print(result_scipy)
				
			

Example 4 Scipy Percentages Growth Rate

Growth Rate
				
					percentages = [10, 15, 20, -5]
				
			
				
					decimal_values = [(1 + p / 100) for p in percentages]
				
			
				
					geometric_mean_decimal = gmean(decimal_values)
				
			
				
					geometric_mean_decimal
				
			
				
					geometric_mean_percentage = (geometric_mean_decimal - 1) * 100
				
			
				
					geometric_mean_percentage
				
			

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 *