| 1 |
#!/usr/bin/env python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
"""Mean, weighted mean, median, and weighted median. |
| 4 |
|
| 5 |
WeightedStats includes four functions (mean, weighted_mean, median, |
| 6 |
weighted_median) which accept lists as arguments, and two functions |
| 7 |
(numpy_weighted_mean, numpy weighted_median) which accept either lists |
| 8 |
or numpy arrays. |
| 9 |
|
| 10 |
Example: |
| 11 |
|
| 12 |
import weightedstats as ws |
| 13 |
|
| 14 |
my_data = [1, 2, 3, 4, 5] |
| 15 |
my_weights = [10, 1, 1, 1, 9] |
| 16 |
|
| 17 |
# Ordinary (unweighted) mean and median |
| 18 |
ws.mean(my_data) # equivalent to ws.weighted_mean(my_data) |
| 19 |
ws.median(my_data) # equivalent to ws.weighted_median(my_data) |
| 20 |
|
| 21 |
# Weighted mean and median |
| 22 |
ws.weighted_mean(my_data, weights=my_weights) |
| 23 |
ws.weighted_median(my_data, weights=my_weights) |
| 24 |
|
| 25 |
# Special weighted mean and median functions for use with numpy arrays |
| 26 |
ws.numpy_weighted_mean(my_data, weights=my_weights) |
| 27 |
ws.numpy_weighted_median(my_data, weights=my_weights) |
| 28 |
|
| 29 |
""" |
| 30 |
from __future__ import division |
| 31 |
import sys |
| 32 |
|
| 33 |
__title__ = "WeightedStats" |
| 34 |
__version__ = "0.4.1" |
| 35 |
__author__ = "Jack Peterson" |
| 36 |
__email__ = "[email protected]" |
| 37 |
__license__ = "MIT" |
| 38 |
|
| 39 |
def mean(data): |
| 40 |
"""Calculate the mean of a list.""" |
| 41 |
return sum(data) / float(len(data)) |
| 42 |
|
| 43 |
def weighted_mean(data, weights=None): |
| 44 |
"""Calculate the weighted mean of a list.""" |
| 45 |
if weights is None: |
| 46 |
return mean(data) |
| 47 |
total_weight = float(sum(weights)) |
| 48 |
weights = [weight / total_weight for weight in weights] |
| 49 |
w_mean = 0 |
| 50 |
for i, weight in enumerate(weights): |
| 51 |
w_mean += weight * data[i] |
| 52 |
return w_mean |
| 53 |
|
| 54 |
def numpy_weighted_mean(data, weights=None): |
| 55 |
"""Calculate the weighted mean of an array/list using numpy.""" |
| 56 |
import numpy as np |
| 57 |
weights = np.array(weights).flatten() / float(sum(weights)) |
| 58 |
return np.dot(np.array(data), weights) |
| 59 |
|
| 60 |
def median(data): |
| 61 |
"""Calculate the median of a list.""" |
| 62 |
data.sort() |
| 63 |
num_values = len(data) |
| 64 |
half = num_values // 2 |
| 65 |
if num_values % 2: |
| 66 |
return data[half] |
| 67 |
return 0.5 * (data[half-1] + data[half]) |
| 68 |
|
| 69 |
def weighted_median(data, weights=None): |
| 70 |
"""Calculate the weighted median of a list.""" |
| 71 |
if weights is None: |
| 72 |
return median(data) |
| 73 |
midpoint = 0.5 * sum(weights) |
| 74 |
if any([j > midpoint for j in weights]): |
| 75 |
return data[weights.index(max(weights))] |
| 76 |
if any([j > 0 for j in weights]): |
| 77 |
sorted_data, sorted_weights = zip(*sorted(zip(data, weights))) |
| 78 |
cumulative_weight = 0 |
| 79 |
below_midpoint_index = 0 |
| 80 |
while cumulative_weight <= midpoint: |
| 81 |
below_midpoint_index += 1 |
| 82 |
cumulative_weight += sorted_weights[below_midpoint_index-1] |
| 83 |
cumulative_weight -= sorted_weights[below_midpoint_index-1] |
| 84 |
if abs(cumulative_weight - midpoint) < sys.float_info.epsilon: |
| 85 |
bounds = sorted_data[below_midpoint_index-2:below_midpoint_index] |
| 86 |
return sum(bounds) / float(len(bounds)) |
| 87 |
return sorted_data[below_midpoint_index-1] |
| 88 |
|
| 89 |
def numpy_weighted_median(data, weights=None): |
| 90 |
"""Calculate the weighted median of an array/list using numpy.""" |
| 91 |
import numpy as np |
| 92 |
if weights is None: |
| 93 |
return np.median(np.array(data).flatten()) |
| 94 |
data, weights = np.array(data).flatten(), np.array(weights).flatten() |
| 95 |
if any(weights > 0): |
| 96 |
sorted_data, sorted_weights = map(np.array, zip(*sorted(zip(data, weights)))) |
| 97 |
midpoint = 0.5 * sum(sorted_weights) |
| 98 |
if any(weights > midpoint): |
| 99 |
return (data[weights == np.max(weights)])[0] |
| 100 |
cumulative_weight = np.cumsum(sorted_weights) |
| 101 |
below_midpoint_index = np.where(cumulative_weight <= midpoint)[0][-1] |
| 102 |
if np.abs(cumulative_weight[below_midpoint_index] - midpoint) < sys.float_info.epsilon: |
| 103 |
return np.mean(sorted_data[below_midpoint_index:below_midpoint_index+2]) |
| 104 |
return sorted_data[below_midpoint_index+1] |