diff --git a/doc/release/upcoming_changes/27661.compatibility.rst b/doc/release/upcoming_changes/27661.compatibility.rst new file mode 100644 index 000000000000..0482f876766c --- /dev/null +++ b/doc/release/upcoming_changes/27661.compatibility.rst @@ -0,0 +1,5 @@ +* `numpy.cov` now properly transposes single-row (2d array) design matrices + when ``rowvar=False``. Previously, single-row design matrices would + return a scalar in this scenario, which is not correct, so this + is a behavior change and an array of the appropriate shape will + now be returned. diff --git a/numpy/lib/_function_base_impl.py b/numpy/lib/_function_base_impl.py index ce9b3c0cd8c9..aedd8663ecc5 100644 --- a/numpy/lib/_function_base_impl.py +++ b/numpy/lib/_function_base_impl.py @@ -2736,7 +2736,7 @@ def cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, dtype = np.result_type(m, y, np.float64) X = array(m, ndmin=2, dtype=dtype) - if not rowvar and X.shape[0] != 1: + if not rowvar and m.ndim != 1: X = X.T if X.shape[0] == 0: return np.array([]).reshape(0, 0) diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py index 172992ff5fd0..9c33321df77f 100644 --- a/numpy/lib/tests/test_function_base.py +++ b/numpy/lib/tests/test_function_base.py @@ -2509,6 +2509,12 @@ def test_cov_dtype(self, test_type): res = cov(cast_x1, dtype=test_type) assert test_type == res.dtype + def test_gh_27658(self): + x = np.ones((3, 1)) + expected = np.cov(x, ddof=0, rowvar=True) + actual = np.cov(x.T, ddof=0, rowvar=False) + assert_allclose(actual, expected, strict=True) + class Test_I0: