Python  

How to Find the Weighted Average of an Array of Numbers in Python

Table of Contents

  • Introduction

  • What Is a Weighted Average—and Why HR Needs It

  • Core Methods to Compute Weighted Averages in Python

  • Real-World Scenario: Calculating Employee Performance Scores

  • Time and Space Complexity

  • Complete, Production-Ready Implementation

  • Best Practices & Quick Wins

  • Conclusion

Introduction

In modern HR Management Systems (HRMS), not all feedback carries equal weight. A senior manager’s review should influence an employee’s final rating more than a peer’s casual comment. This is where the weighted average becomes essential. Unlike a simple mean, a weighted average accounts for the importance (or weight) of each value—making it perfect for performance evaluations, compensation planning, and promotion decisions. This guide shows you how to compute weighted averages correctly, safely, and efficiently in Python—with a real HRMS use case and zero tolerance for bugs.

What Is a Weighted Average—and Why HR Needs It

The weighted average is calculated as:

dasdad

In HR, this means:

  • Leadership feedback might have a weight of 3.0

  • Peer reviews: 1.0

  • Self-assessments: 0.5

Without weighting, you risk diluting critical insights with low-impact inputs—leading to unfair ratings or missed promotions.

Core Methods to Compute Weighted Averages in Python

1. Manual Calculation (Transparent & Safe)

def weighted_average(values, weights):
    if not values or not weights or len(values) != len(weights):
        raise ValueError("Values and weights must be non-empty and same length")
    if sum(weights) == 0:
        raise ValueError("Sum of weights cannot be zero")
    return sum(v * w for v, w in zip(values, weights)) / sum(weights)

2. Using NumPy (For Large HR Datasets)

import numpy as np

def weighted_average_numpy(values, weights):
    values, weights = np.array(values), np.array(weights)
    if values.size == 0 or weights.size == 0 or values.size != weights.size:
        raise ValueError("Invalid input arrays")
    if np.sum(weights) == 0:
        raise ValueError("Sum of weights is zero")
    return np.average(values, weights=weights)

Optimized for 10,000+ employee records; leverages C-level speed.

Never skip input validation—even NumPy can’t guess your intent.

Real-World Scenario: Calculating Employee Performance Scores

Problem:
Your HRMS collects performance scores from multiple sources:

  • Manager: score=4.5, weight=3.0

  • Two peers: scores=[3.8, 4.0], weights=[1.0, 1.0]

  • Self-review: score=4.2, weight=0.5

You need a single, defensible rating for the employee’s file—used in bonus calculations and promotion eligibility.

Requirements:

  • Handle missing or mismatched inputs gracefully

  • Prevent division by zero

  • Never expose raw scores in logs

  • Return a precise float (e.g., 4.12)

Time and Space Complexity

  • Time: O(n) — you must process each score-weight pair once.

  • Space: O(1) extra memory (no copies needed).

  • NumPy adds minor overhead for small lists but scales better for enterprise HRMS with thousands of employees.

For most teams (<1,000 employees), the manual method is faster and clearer.

Complete, Production-Ready Implementation

from typing import List, Union

def calculate_performance_rating(
    scores: List[Union[int, float]], 
    weights: List[Union[int, float]]
) -> float:
    """
    Compute a fair, weighted performance rating for HRMS.
    
    Args:
        scores: List of performance scores (e.g., [4.5, 3.8, 4.0, 4.2])
        weights: Corresponding importance weights (e.g., [3.0, 1.0, 1.0, 0.5])
        
    Returns:
        float: Weighted average rating, rounded to 2 decimals
        
    Raises:
        ValueError: On invalid input (empty, mismatched, or zero-weight sum)
    """
    if not scores or not weights:
        raise ValueError("Scores and weights cannot be empty")
    if len(scores) != len(weights):
        raise ValueError("Scores and weights must have the same length")
    
    total_weight = sum(weights)
    if total_weight == 0:
        raise ValueError("Total weight cannot be zero")
    
    weighted_sum = sum(score * weight for score, weight in zip(scores, weights))
    return round(weighted_sum / total_weight, 2)


# Example usage in HRMS
if __name__ == "__main__":
    employee_scores = [4.5, 3.8, 4.0, 4.2]
    employee_weights = [3.0, 1.0, 1.0, 0.5]
    
    try:
        rating = calculate_performance_rating(employee_scores, employee_weights)
        print(f"Final Performance Rating: {rating}")
    except ValueError as e:
        print(f"Error calculating rating: {e}")

vfdsx

Best Practices & Quick Wins

  • Always validate input lengths and weights—HR data pipelines can be messy.

  • Round results to 2 decimals for consistency in reports.

  • Raise clear errors—never return None or 0 silently.

  • Never log raw scores or weights—treat them as sensitive HR data.

  • Use type hints (List[Union[int, float]]) to catch bugs early.

Conclusion

A weighted average isn’t just math—it’s fairness engineered into code. In HRMS systems, it ensures that high-impact feedback shapes outcomes, while noise is appropriately discounted. By using a simple, validated function like calculate_performance_rating, you get:

  • Audit-ready logic

  • Protection against edge cases

  • Compliance with data integrity standards

Whether you’re evaluating one employee or ten thousand, the right weighted average implementation builds trust—one fair rating at a time.