diff --git a/doc/source/whatsnew/v2.0.1.rst b/doc/source/whatsnew/v2.0.1.rst index 4380c4c1608c8..939473f132bcb 100644 --- a/doc/source/whatsnew/v2.0.1.rst +++ b/doc/source/whatsnew/v2.0.1.rst @@ -17,6 +17,7 @@ Fixed regressions - Fixed regression in :meth:`Series.describe` showing ``RuntimeWarning`` for extension dtype :class:`Series` with one element (:issue:`52515`) - Fixed regression in :meth:`DataFrame.sort_values` not resetting index when :class:`DataFrame` is already sorted and ``ignore_index=True`` (:issue:`52553`) - Fixed regression in :meth:`MultiIndex.isin` raising ``TypeError`` for ``Generator`` (:issue:`52568`) +- Fixed regression in :meth:`DataFrame.pivot` changing :class:`Index` name of input object (:issue:`52629`) .. --------------------------------------------------------------------------- .. _whatsnew_201.bug_fixes: diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index 3ed3f1953f089..0f775f959c4ce 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -519,6 +519,8 @@ def pivot( # If columns is None we will create a MultiIndex level with None as name # which might cause duplicated names because None is the default for # level names + data = data.copy(deep=False) + data.index = data.index.copy() data.index.names = [ name if name is not None else lib.NoDefault for name in data.index.names ] diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index 3df16d876638a..3fc617b91b866 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -2591,3 +2591,10 @@ def test_pivot_values_is_none(self): result = df.pivot(columns="b", values=None) expected = DataFrame(1, index=[0], columns=Index([2], name="b")) tm.assert_frame_equal(result, expected) + + def test_pivot_not_changing_index_name(self): + # GH#52692 + df = DataFrame({"one": ["a"], "two": 0, "three": 1}) + expected = df.copy(deep=True) + df.pivot(index="one", columns="two", values="three") + tm.assert_frame_equal(df, expected)