def weightedAverage(valueWeightList):
'''
Takes a list of tuples (value, weight) and
returns weighted average as calculated by
Sum of all values * weights / Sum of all weights
'''
numerator = sum([v * w for v,w in valueWeightList])
denominator = sum([w for v,w in valueWeightList])
if(denominator != 0):
return(float(numerator) / float(denominator))
else:
return None
.NET
(1)
AIR
(1)
Algorithms
(1)
ArcGIS
(2)
ArcGIS Server
(7)
ArcMap
(2)
ArcObjects
(6)
arcpy
(1)
Arrays
(1)
AS3
(1)
Bing
(1)
C#
(8)
Clean Code
(1)
Clustering
(1)
COM
(1)
Design Patterns
(1)
Developer Interviews
(1)
Django
(1)
ESRI Developer Summit
(3)
ESRI Flex API
(1)
Flash
(1)
Flex
(7)
fuzzy
(1)
Geometry
(1)
Geoprocessing
(3)
Google
(1)
Imaging
(1)
JavaScript
(2)
Map Tiles
(2)
Mobile
(1)
Nokia
(1)
Offline Mapping
(2)
PIL
(1)
Pixel Bender
(1)
Presentations
(1)
PSU
(2)
PyTables
(1)
Python
(18)
Rasters
(2)
Server Object Extensions
(4)
Sorting
(1)
Spatial Analysis
(1)
SQLite
(1)
Sublime Text 2
(1)
VB
(2)
War
(1)
Where Camp
(1)
Yahoo
(1)
14.8.10
Simple Weighted Average with Python
While I suspect there must already be a built in weighted average tool in some python library ( scipy / numpy), for a project I'm working on I just wrote my own. I would love to hear what people think and if I can improve the function in any way.
Subscribe to:
Post Comments (Atom)
Nice and simple, although you don't need the list comprehension square brackets any more (unless you need to support older versions of Python). Thanks!
ReplyDeleteHey no problem. Unfortunately I'm still stuck in the 2.x Python world :(
ReplyDelete