From 630fed2e1c48363ba7041a74ad46785e9679cddd Mon Sep 17 00:00:00 2001 From: Matthew Roeschke <10647082+mroeschke@users.noreply.github.com> Date: Thu, 25 Jan 2024 17:46:08 -0800 Subject: [PATCH 1/2] BUG: np.matmul with Index raising TypeError --- doc/source/whatsnew/v3.0.0.rst | 2 +- pandas/core/indexes/base.py | 3 +++ pandas/tests/series/test_ufunc.py | 7 +++++++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index 950082f9281c5..9de485e53b32d 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -142,7 +142,7 @@ Timezones Numeric ^^^^^^^ -- +- Bug in ``np.matmul`` with :class:`Index` inputs raising a ``TypeError`` (:issue:`?`) - Conversion diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index bf20525e2c7fd..4b200c447cb4d 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -951,6 +951,9 @@ def __array_ufunc__(self, ufunc: np.ufunc, method: str_t, *inputs, **kwargs): elif method == "reduce": result = lib.item_from_zerodim(result) return result + elif is_scalar(result): + # e.g. matmul + return result if result.dtype == np.float16: result = result.astype(np.float32) diff --git a/pandas/tests/series/test_ufunc.py b/pandas/tests/series/test_ufunc.py index 9d13ebf740eab..3ef319174313d 100644 --- a/pandas/tests/series/test_ufunc.py +++ b/pandas/tests/series/test_ufunc.py @@ -427,6 +427,13 @@ def test_np_matmul(): tm.assert_frame_equal(expected, result) +@pytest.mark.parametrize("box", [pd.Index, pd.Series]) +def test_np_matmul_1D(box): + result = np.matmul(box([1, 2]), box([2, 3])) + assert result == 8 + assert isinstance(result, np.int64) + + def test_array_ufuncs_for_many_arguments(): # GH39853 def add3(x, y, z): From 5de0ee512d144f6f7d18af49ab7d0a176cba0c8c Mon Sep 17 00:00:00 2001 From: Matthew Roeschke <10647082+mroeschke@users.noreply.github.com> Date: Thu, 25 Jan 2024 17:47:06 -0800 Subject: [PATCH 2/2] Add whatsnew number --- doc/source/whatsnew/v3.0.0.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index 9de485e53b32d..7f2c90bc89a9a 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -142,7 +142,7 @@ Timezones Numeric ^^^^^^^ -- Bug in ``np.matmul`` with :class:`Index` inputs raising a ``TypeError`` (:issue:`?`) +- Bug in ``np.matmul`` with :class:`Index` inputs raising a ``TypeError`` (:issue:`57079`) - Conversion