Skip to content

Commit 9df5143

Browse files
committed
BUG: numpy.ma.polyfit masks NaNs incorrectly
This fixes the incorrect handing of masked NaNs by ``np.ma.polyfit``. Instead of passing the mask into ``np.polyfit`` by setting the weight of the masked points to zero, the subset of elements of which are to be fitted are passed instead. Closes numpy#5591
1 parent d770034 commit 9df5143

File tree

2 files changed

+20
-5
lines changed

2 files changed

+20
-5
lines changed

numpy/ma/extras.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1921,12 +1921,12 @@ def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False):
19211921
m = mask_or(m, getmask(w))
19221922

19231923
if m is not nomask:
1924+
not_m = ~m
19241925
if w is not None:
1925-
w = ~m*w
1926-
else:
1927-
w = ~m
1928-
1929-
return np.polyfit(x, y, deg, rcond, full, w, cov)
1926+
w = w[not_m]
1927+
return np.polyfit(x[not_m], y[not_m], deg, rcond, full, w, cov)
1928+
else:
1929+
return np.polyfit(x, y, deg, rcond, full, w, cov)
19301930

19311931
polyfit.__doc__ = ma.doc_note(np.polyfit.__doc__, polyfit.__doc__)
19321932

numpy/ma/tests/test_extras.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -734,6 +734,21 @@ def test_polyfit(self):
734734
for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)):
735735
assert_almost_equal(a, a_)
736736

737+
def test_polyfit_with_masked_NaNs(self):
738+
x = np.random.rand(10)
739+
y = np.random.rand(20).reshape(-1, 2)
740+
741+
x[0] = np.nan
742+
y[-1,-1] = np.nan
743+
x = x.view(MaskedArray)
744+
y = y.view(MaskedArray)
745+
x[0] = masked
746+
y[-1,-1] = masked
747+
748+
(C, R, K, S, D) = polyfit(x, y, 3, full=True)
749+
(c, r, k, s, d) = np.polyfit(x[1:-1], y[1:-1,:], 3, full=True)
750+
for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)):
751+
assert_almost_equal(a, a_)
737752

738753
class TestArraySetOps(TestCase):
739754

0 commit comments

Comments
 (0)