From e760892a86886ad08bbd7740763e1fc21863c1af Mon Sep 17 00:00:00 2001 From: Patrick Hoefler Date: Mon, 13 Mar 2023 20:38:44 +0000 Subject: [PATCH 1/2] BUG: swapaxes creating result with read_only array --- pandas/core/generic.py | 2 +- pandas/tests/copy_view/test_methods.py | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 5b77bb9651073..c8df78a26f355 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -750,7 +750,7 @@ def swapaxes( mapping = {i: j, j: i} new_axes = [self._get_axis(mapping.get(k, k)) for k in range(self._AXIS_LEN)] - new_values = self.values.swapaxes(i, j) + new_values = self._values.swapaxes(i, j) if ( using_copy_on_write() and self._mgr.is_single_block diff --git a/pandas/tests/copy_view/test_methods.py b/pandas/tests/copy_view/test_methods.py index 7429a73717470..37d89a2ad4f85 100644 --- a/pandas/tests/copy_view/test_methods.py +++ b/pandas/tests/copy_view/test_methods.py @@ -641,6 +641,14 @@ def test_swapaxes_single_block(using_copy_on_write): tm.assert_frame_equal(df, df_orig) +def test_swapaxes_read_only_array(): + df = DataFrame({"a": [1, 2], "b": 3}) + df = df.swapaxes(axis1="index", axis2="columns") + df.iloc[0, 0] = 100 + expected = DataFrame({0: [100, 3], 1: [2, 3]}, index=["a", "b"]) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize( "method, idx", [ From 7432a7269c87b58cc9c1f30ebc3c14511c7cda8d Mon Sep 17 00:00:00 2001 From: Patrick Hoefler Date: Tue, 14 Mar 2023 11:57:53 +0100 Subject: [PATCH 2/2] Fix mypy --- pandas/core/generic.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index c8df78a26f355..de99effdfe579 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -750,7 +750,7 @@ def swapaxes( mapping = {i: j, j: i} new_axes = [self._get_axis(mapping.get(k, k)) for k in range(self._AXIS_LEN)] - new_values = self._values.swapaxes(i, j) + new_values = self._values.swapaxes(i, j) # type: ignore[union-attr] if ( using_copy_on_write() and self._mgr.is_single_block