summaryrefslogtreecommitdiff
path: root/numpy/lib/function_base.py
diff options
context:
space:
mode:
authorAllan Haldane <allan.haldane@gmail.com>2016-03-05 15:52:04 -0500
committerAllan Haldane <allan.haldane@gmail.com>2016-03-07 12:41:14 -0500
commit5ceab8f982d80c68b3b5e90697cd20df51f4a3e8 (patch)
tree82a494e17ed9bff0307753f0a75e23c68fbb665b /numpy/lib/function_base.py
parent8c4048a1dbc2bee0cc756ece29166863fbdcc748 (diff)
downloadnumpy-5ceab8f982d80c68b3b5e90697cd20df51f4a3e8.tar.gz
MAINT: cleanup np.average
Diffstat (limited to 'numpy/lib/function_base.py')
-rw-r--r--numpy/lib/function_base.py21
1 files changed, 13 insertions, 8 deletions
diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py
index 5c1654fc3..efa51173a 100644
--- a/numpy/lib/function_base.py
+++ b/numpy/lib/function_base.py
@@ -898,15 +898,19 @@ def average(a, axis=None, weights=None, returned=False):
TypeError: Axis must be specified when shapes of a and weights differ.
"""
- if not isinstance(a, np.matrix):
- a = np.asarray(a)
+ a = np.asanyarray(a)
if weights is None:
avg = a.mean(axis)
scl = avg.dtype.type(a.size/avg.size)
else:
- a = a + 0.0
- wgt = np.asarray(weights)
+ wgt = np.asanyarray(weights)
+
+ if issubclass(a.dtype.type, (np.integer, np.bool_)):
+ result_dtype = np.result_type(a.dtype, wgt.dtype, 'f8')
+ else:
+ result_dtype = np.result_type(a.dtype, wgt.dtype)
+
# Sanity checks
if a.shape != wgt.shape:
if axis is None:
@@ -921,17 +925,18 @@ def average(a, axis=None, weights=None, returned=False):
"Length of weights not compatible with specified axis.")
# setup wgt to broadcast along axis
- wgt = np.array(wgt, copy=0, ndmin=a.ndim).swapaxes(-1, axis)
+ wgt = np.broadcast_to(wgt, (a.ndim-1)*(1,) + wgt.shape)
+ wgt = wgt.swapaxes(-1, axis)
- scl = wgt.sum(axis=axis, dtype=np.result_type(a.dtype, wgt.dtype))
+ scl = wgt.sum(axis=axis, dtype=result_dtype)
if (scl == 0.0).any():
raise ZeroDivisionError(
"Weights sum to zero, can't be normalized")
- avg = np.multiply(a, wgt).sum(axis)/scl
+ avg = np.multiply(a, wgt, dtype=result_dtype).sum(axis)/scl
if returned:
- scl = np.multiply(avg, 0) + scl
+ scl = np.broadcast_to(scl, avg.shape)
return avg, scl
else:
return avg