diff options
author | Sebastian Berg <sebastian@sipsolutions.net> | 2022-09-03 17:50:59 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-09-03 17:50:59 +0200 |
commit | 2a6daf39cc4fd895ab803edf018907cb8044f821 (patch) | |
tree | 2304fbd0b29813452e8fea297f45b7751f6adcef /numpy/lib | |
parent | 005aa4314d6002d1331b7e77e7fe39b70e202a49 (diff) | |
parent | 25d5e385ec537f911702f905ca050815e320865a (diff) | |
download | numpy-2a6daf39cc4fd895ab803edf018907cb8044f821.tar.gz |
Merge pull request #22009 from eendebakpt/fix/average
BUG: fix np.average for Fraction elements
Diffstat (limited to 'numpy/lib')
-rw-r--r-- | numpy/lib/function_base.py | 9 | ||||
-rw-r--r-- | numpy/lib/tests/test_function_base.py | 5 |
2 files changed, 10 insertions, 4 deletions
diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index af890183e..15e24a0d9 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -516,7 +516,8 @@ def average(a, axis=None, weights=None, returned=False, *, if weights is None: avg = a.mean(axis, **keepdims_kw) - scl = avg.dtype.type(a.size/avg.size) + avg_as_array = np.asanyarray(avg) + scl = avg_as_array.dtype.type(a.size/avg_as_array.size) else: wgt = np.asanyarray(weights) @@ -547,12 +548,12 @@ def average(a, axis=None, weights=None, returned=False, *, raise ZeroDivisionError( "Weights sum to zero, can't be normalized") - avg = np.multiply(a, wgt, + avg = avg_as_array = np.multiply(a, wgt, dtype=result_dtype).sum(axis, **keepdims_kw) / scl if returned: - if scl.shape != avg.shape: - scl = np.broadcast_to(scl, avg.shape).copy() + if scl.shape != avg_as_array.shape: + scl = np.broadcast_to(scl, avg_as_array.shape).copy() return avg, scl else: return avg diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py index 56081b4f0..277843222 100644 --- a/numpy/lib/tests/test_function_base.py +++ b/numpy/lib/tests/test_function_base.py @@ -421,6 +421,11 @@ class TestAverage: w /= w.sum() assert_almost_equal(a.mean(0), average(a, weights=w)) + def test_average_class_without_dtype(self): + # see gh-21988 + a = np.array([Fraction(1, 5), Fraction(3, 5)]) + assert_equal(np.average(a), Fraction(2, 5)) + class TestSelect: choices = [np.array([1, 2, 3]), np.array([4, 5, 6]), |