CodexBloom - Programming Q&A Platform

How to implement guide with np.percentile returning unexpected results for weighted data in numpy 1.24.3

👀 Views: 56 💬 Answers: 1 📅 Created: 2025-07-06
numpy percentile weights Python

I've been banging my head against this for hours. I'm having a hard time understanding Quick question that's been bugging me - I'm working with an scenario with `np.percentile` when trying to calculate percentiles for a weighted array in NumPy 1.24.3. The function is supposed to handle weights, but it seems to return results that don't align with my expectations. Here’s the code I’m using: ```python import numpy as np data = np.array([1, 2, 3, 4, 5]) weights = np.array([0.1, 0.2, 0.3, 0.2, 0.2]) percentile = 50 result = np.percentile(data, percentile, weights=weights) print(result) ``` When I run this code, I get an output of `3.0`, which I expected to be influenced by the weights I've assigned. However, I thought that the weighted percentile should give more importance to the higher values since they have greater weights. I also tried using `np.average` to validate the weighted average, and it returned `3.0`, which confirms that the weights are indeed being applied as expected, leading me to believe that something is off with the way `np.percentile` interprets the weights. I’ve checked the documentation, and while it mentions weights, it doesn’t clarify how they interact with the percentile calculation. Could someone explain if I’m using it incorrectly or if there’s a specific way to apply weights with `np.percentile` to get the correct result? Any insights or examples would be greatly appreciated. What's the best practice here? The project is a CLI tool built with Python. Thanks in advance! I'm using Python LTS in this project. My development environment is CentOS. Any suggestions would be helpful.