pax_global_header00006660000000000000000000000064136163711450014521gustar00rootroot0000000000000052 comment=9b970d9bf59021bc55cba87c275fb8b1348e2a3b weightedstats-0.4.1/000077500000000000000000000000001361637114500144025ustar00rootroot00000000000000weightedstats-0.4.1/.gitignore000066400000000000000000000012521361637114500163720ustar00rootroot00000000000000venv/ # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .cache nosetests.xml coverage.xml # Translations *.mo *.pot # Django stuff: *.log # Sphinx documentation docs/_build/ # PyBuilder target/ weightedstats-0.4.1/.travis.yml000066400000000000000000000004661361637114500165210ustar00rootroot00000000000000language: python notifications: email: false python: - "2.7" - "3.5" - "3.6" install: - "easy_install -U setuptools" - "pip install ." - "pip install -r test_requirements.txt" script: - py.test test --doctest-modules -v --cov weightedstats --cov-report term-missing after_success: - coverallsweightedstats-0.4.1/LICENSE.txt000066400000000000000000000020561361637114500162300ustar00rootroot00000000000000Copyright (c) 2014, Jack Peterson, Dyffy Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. weightedstats-0.4.1/MANIFEST.in000066400000000000000000000001001361637114500161270ustar00rootroot00000000000000include MANIFEST.in LICENSE.txt README.rst test_requirements.txtweightedstats-0.4.1/README.rst000066400000000000000000000030361361637114500160730ustar00rootroot00000000000000WeightedStats ============= .. image:: https://travis-ci.org/tinybike/weightedstats.svg?branch=master :target: https://travis-ci.org/tinybike/weightedstats .. image:: https://coveralls.io/repos/github/tinybike/weightedstats/badge.svg?branch=master :target: https://coveralls.io/github/tinybike/weightedstats?branch=master .. image:: https://badge.fury.io/py/weightedstats.svg :target: http://badge.fury.io/py/weightedstats Python functions to calculate the mean, weighted mean, median, and weighted median. Installation ^^^^^^^^^^^^ The easiest way to install WeightedStats is to use pip:: $ pip install weightedstats Usage ^^^^^ WeightedStats includes four functions (mean, weighted_mean, median, weighted_median) which accept lists as arguments, and two functions (numpy_weighted_mean, numpy weighted_median) which accept either lists or numpy arrays. Example: .. code-block:: python import weightedstats as ws my_data = [1, 2, 3, 4, 5] my_weights = [10, 1, 1, 1, 9] # Ordinary (unweighted) mean and median ws.mean(my_data) # equivalent to ws.weighted_mean(my_data) ws.median(my_data) # equivalent to ws.weighted_median(my_data) # Weighted mean and median ws.weighted_mean(my_data, weights=my_weights) ws.weighted_median(my_data, weights=my_weights) # Special weighted mean and median functions for use with numpy arrays ws.numpy_weighted_mean(my_data, weights=my_weights) ws.numpy_weighted_median(my_data, weights=my_weights) Tests ^^^^^ Unit tests are in the test/ directory. weightedstats-0.4.1/setup.py000066400000000000000000000014251361637114500161160ustar00rootroot00000000000000#!/usr/bin/env python try: from setuptools import setup except ImportError: from distutils.core import setup with open("README.rst", "r") as fh: long_description = fh.read() setup( name="weightedstats", version="0.4.1", description="Mean, weighted mean, median, weighted median", long_description=long_description, long_description_content_type="text/x-rst", author="Jack Peterson", author_email="", maintainer="Jack Peterson", maintainer_email="", license="MIT", url="https://github.com/tinybike/weightedstats", download_url = "https://github.com/tinybike/weightedstats/tarball/0.4.1", packages=["weightedstats"], keywords = ["weights", "mean", "median", "numpy", "statistics"] ) weightedstats-0.4.1/test/000077500000000000000000000000001361637114500153615ustar00rootroot00000000000000weightedstats-0.4.1/test/test_weightedstats.py000066400000000000000000000104371361637114500216560ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- """ Tests for weighted stats functions. """ from __future__ import division import os import sys import platform import unittest HERE = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.join(HERE, os.pardir)) from weightedstats import * class TestWeightedStats(unittest.TestCase): def setUp(self): self.data = [ [7, 1, 2, 4, 10], [7, 1, 2, 4, 10], [7, 1, 2, 4, 10, 15], [1, 2, 4, 7, 10, 15], [0, 10, 20, 30], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [30, 40, 50, 60, 35], [2, 0.6, 1.3, 0.3, 0.3, 1.7, 0.7, 1.7, 0.4], [3.7, 3.3, 3.5, 2.8], [100, 125, 123, 60, 45, 56, 66], [2, 2, 2, 2, 2, 2], [2.3], [-2, -3, 1, 2, -10], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [5, 4, 3, 2, 1], [-2, 2, -1, 3, 6], [-10, 1, 1, -10, -10], [2, 4], [2, 2, 4, 4], [2, 2, 2, 4], ] self.weights = [ [1, 1/3, 1/3, 1/3, 1], [1, 1, 1, 1, 1], [1, 1/3, 1/3, 1/3, 1, 1], [1/3, 1/3, 1/3, 1, 1, 1], [30, 191, 9, 0], [10, 1, 1, 1, 9], [10, 1, 1, 1, 900], [1, 3, 5, 4, 2], [2, 2, 0, 1, 2, 2, 1, 6, 0], [5, 5, 4, 1], [30, 56, 144, 24, 55, 43, 67], [0.1, 0.2, 0.3, 0.4, 0.5, 0.6], [12], [7, 1, 1, 1, 6], [1, 0, 0, 0, 2], [10, 1, 1, 1, 9], [10, 1, 1, 1, 10], [1, 2, -3, 4, -5], [0.1, 0.2, 0.3, -0.2, 0.1], [-1, -1, -1, -1, 1], [1, 1], [1, 1, 1, 1], [1, 1, 1, 1], ] self.median_answers = [7.0, 4.0, 8.5, 8.5, 10.0, 2.5, 5.0, 50.0, 1.7, 3.5, 100.0, 2.0, 2.3, -2.0, 5.0, 2.5, 3.0, 2.0, -1.0, -10.0, 3.0, 3.0, 2.0] self.mean_answers = [6.444444, 4.800000, 8.583333, 8.583333, 9.086956, 2.909091, 4.949617, 47.333333, 1.275000, 3.453333, 91.782816, 2.000000, 2.300000, -4.625000, 3.666667, 2.909091, 3.000000, -7.000000, -0.200000, -2.666667, 3.000000, 3.000000, 2.500000] def test_mean(self): datum = [7, 1, 1, 1, 6] self.assertTrue(weighted_mean(datum) == mean(datum) == 3.2) def test_weighted_mean(self): for datum, weight, answer in zip(self.data, self.weights, self.mean_answers): self.assertTrue(abs(weighted_mean(datum, weights=weight) - answer) <= 1e-6) def test_numpy_weighted_mean(self): for datum, weight, answer in zip(self.data, self.weights, self.mean_answers): self.assertTrue(abs(numpy_weighted_mean(datum, weights=weight) - answer) <= 1e-6) def test_median(self): datum = [4, 3, 2, 1] self.assertTrue(weighted_median(datum) == numpy_weighted_median(datum) == median(datum) == 2.5) datum = [7, 1, 1, 1, 6] self.assertTrue(weighted_median(datum) == numpy_weighted_median(datum) == median(datum) == 1.0) def test_weighted_median(self): for datum, weight, answer in zip(self.data, self.weights, self.median_answers): self.assertTrue(abs(weighted_median(datum, weights=weight) - answer) <= 1e-16) self.assertTrue(weighted_median([4, 3, 2, 1], weights=[0, 0, 0, 0]) is None) def test_numpy_weighted_median(self): for datum, weight, answer in zip(self.data, self.weights, self.median_answers): self.assertTrue(abs(numpy_weighted_median(datum, weights=weight) - answer) <= 1e-16) self.assertTrue(numpy_weighted_median([4, 3, 2, 1], weights=[0, 0, 0, 0]) is None) if __name__ == "__main__": suite = unittest.TestLoader().loadTestsFromTestCase(TestWeightedStats) unittest.TextTestRunner(verbosity=2).run(suite) weightedstats-0.4.1/test_requirements.txt000066400000000000000000000000531361637114500207230ustar00rootroot00000000000000numpy pytest pytest-cov python-coveralls shweightedstats-0.4.1/weightedstats/000077500000000000000000000000001361637114500172615ustar00rootroot00000000000000weightedstats-0.4.1/weightedstats/__init__.py000066400000000000000000000074421361637114500214010ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- """Mean, weighted mean, median, and weighted median. WeightedStats includes four functions (mean, weighted_mean, median, weighted_median) which accept lists as arguments, and two functions (numpy_weighted_mean, numpy weighted_median) which accept either lists or numpy arrays. Example: import weightedstats as ws my_data = [1, 2, 3, 4, 5] my_weights = [10, 1, 1, 1, 9] # Ordinary (unweighted) mean and median ws.mean(my_data) # equivalent to ws.weighted_mean(my_data) ws.median(my_data) # equivalent to ws.weighted_median(my_data) # Weighted mean and median ws.weighted_mean(my_data, weights=my_weights) ws.weighted_median(my_data, weights=my_weights) # Special weighted mean and median functions for use with numpy arrays ws.numpy_weighted_mean(my_data, weights=my_weights) ws.numpy_weighted_median(my_data, weights=my_weights) """ from __future__ import division import sys __title__ = "WeightedStats" __version__ = "0.4.1" __author__ = "Jack Peterson" __email__ = "jack@tinybike.net" __license__ = "MIT" def mean(data): """Calculate the mean of a list.""" return sum(data) / float(len(data)) def weighted_mean(data, weights=None): """Calculate the weighted mean of a list.""" if weights is None: return mean(data) total_weight = float(sum(weights)) weights = [weight / total_weight for weight in weights] w_mean = 0 for i, weight in enumerate(weights): w_mean += weight * data[i] return w_mean def numpy_weighted_mean(data, weights=None): """Calculate the weighted mean of an array/list using numpy.""" import numpy as np weights = np.array(weights).flatten() / float(sum(weights)) return np.dot(np.array(data), weights) def median(data): """Calculate the median of a list.""" data.sort() num_values = len(data) half = num_values // 2 if num_values % 2: return data[half] return 0.5 * (data[half-1] + data[half]) def weighted_median(data, weights=None): """Calculate the weighted median of a list.""" if weights is None: return median(data) midpoint = 0.5 * sum(weights) if any([j > midpoint for j in weights]): return data[weights.index(max(weights))] if any([j > 0 for j in weights]): sorted_data, sorted_weights = zip(*sorted(zip(data, weights))) cumulative_weight = 0 below_midpoint_index = 0 while cumulative_weight <= midpoint: below_midpoint_index += 1 cumulative_weight += sorted_weights[below_midpoint_index-1] cumulative_weight -= sorted_weights[below_midpoint_index-1] if abs(cumulative_weight - midpoint) < sys.float_info.epsilon: bounds = sorted_data[below_midpoint_index-2:below_midpoint_index] return sum(bounds) / float(len(bounds)) return sorted_data[below_midpoint_index-1] def numpy_weighted_median(data, weights=None): """Calculate the weighted median of an array/list using numpy.""" import numpy as np if weights is None: return np.median(np.array(data).flatten()) data, weights = np.array(data).flatten(), np.array(weights).flatten() if any(weights > 0): sorted_data, sorted_weights = map(np.array, zip(*sorted(zip(data, weights)))) midpoint = 0.5 * sum(sorted_weights) if any(weights > midpoint): return (data[weights == np.max(weights)])[0] cumulative_weight = np.cumsum(sorted_weights) below_midpoint_index = np.where(cumulative_weight <= midpoint)[0][-1] if np.abs(cumulative_weight[below_midpoint_index] - midpoint) < sys.float_info.epsilon: return np.mean(sorted_data[below_midpoint_index:below_midpoint_index+2]) return sorted_data[below_midpoint_index+1]