Python Implementation
Basic Weighted Average Calculation
Using Manual Calculation
def weighted_average(values, weights):
"""
Calculate weighted average manually
Args:
values (list): Data values
weights (list): Corresponding weights
Returns:
float: Weighted average
"""
if len(values) != len(weights):
raise ValueError("Values and weights must have equal length")
weighted_sum = sum(value * weight for value, weight in zip(values, weights))
total_weight = sum(weights)
return weighted_sum / total_weight
## Example usage
grades = [90, 85, 88]
credits = [3, 4, 2]
result = weighted_average(grades, credits)
print(f"Weighted Average: {result}")
Advanced Implementations
Using NumPy
import numpy as np
def numpy_weighted_average(values, weights):
"""
Calculate weighted average using NumPy
Args:
values (array-like): Data values
weights (array-like): Corresponding weights
Returns:
float: Weighted average
"""
return np.average(values, weights=weights)
## Example
grades = np.array([90, 85, 88])
credits = np.array([3, 4, 2])
result = numpy_weighted_average(grades, credits)
print(f"NumPy Weighted Average: {result}")
Practical Scenarios
Stock Portfolio Calculation
def portfolio_weighted_average(stocks):
"""
Calculate weighted average stock performance
Args:
stocks (list): List of dictionaries with stock details
Returns:
float: Weighted average stock performance
"""
total_value = sum(stock['value'] for stock in stocks)
weighted_performance = sum(
stock['performance'] * (stock['value'] / total_value)
for stock in stocks
)
return weighted_performance
## Example
portfolio = [
{'name': 'Tech Stock', 'value': 5000, 'performance': 12.5},
{'name': 'Finance Stock', 'value': 3000, 'performance': 8.2},
{'name': 'Energy Stock', 'value': 2000, 'performance': 6.7}
]
avg_performance = portfolio_weighted_average(portfolio)
print(f"Portfolio Weighted Performance: {avg_performance}%")
Error Handling and Validation
def robust_weighted_average(values, weights):
"""
Robust weighted average calculation with comprehensive validation
Args:
values (list): Numerical values
weights (list): Corresponding weights
Returns:
float: Weighted average or None
"""
try:
## Input validation
if not values or not weights:
raise ValueError("Empty input lists")
if len(values) != len(weights):
raise ValueError("Mismatched list lengths")
## Check for non-numeric inputs
if not all(isinstance(v, (int, float)) for v in values + weights):
raise TypeError("Non-numeric values detected")
## Prevent division by zero
if sum(weights) == 0:
raise ZeroDivisionError("Total weight cannot be zero")
weighted_sum = sum(value * weight for value, weight in zip(values, weights))
total_weight = sum(weights)
return weighted_sum / total_weight
except Exception as e:
print(f"Calculation Error: {e}")
return None
Weighted Average Workflow
graph TD
A[Input Values] --> B[Input Weights]
B --> C{Validate Inputs}
C -->|Valid| D[Calculate Weighted Sum]
C -->|Invalid| E[Raise Error]
D --> F[Divide by Total Weight]
F --> G[Return Weighted Average]
At LabEx, we emphasize practical and robust implementation of statistical calculations in Python.