From 16d5c01a185490c3e182f0ff6b2e1b45a26d1eba Mon Sep 17 00:00:00 2001 From: Matthew Roeschke Date: Fri, 31 Dec 2021 10:12:16 -0800 Subject: [PATCH] BUG: DataFrame.pivot(index=None) with MultiIndex --- doc/source/whatsnew/v1.4.0.rst | 1 + pandas/core/reshape/pivot.py | 8 ++++++- pandas/tests/reshape/test_pivot_multilevel.py | 22 +++++++++++++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index a47cee645bf4b..24d102f1640b1 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -964,6 +964,7 @@ Reshaping - Bug in :meth:`Series.unstack` with object doing unwanted type inference on resulting columns (:issue:`44595`) - Bug in :class:`MultiIndex` failing join operations with overlapping ``IntervalIndex`` levels (:issue:`44096`) - Bug in :meth:`DataFrame.replace` and :meth:`Series.replace` results is different ``dtype`` based on ``regex`` parameter (:issue:`44864`) +- Bug in :meth:`DataFrame.pivot` with ``index=None`` when the :class:`DataFrame` index was a :class:`MultiIndex` (:issue:`23955`) Sparse ^^^^^^ diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index fc6db78320169..069f0e5003cdf 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -495,7 +495,13 @@ def pivot( ) else: if index is None: - index_list = [Series(data.index, name=data.index.name)] + if isinstance(data.index, MultiIndex): + # GH 23955 + index_list = [ + data.index.get_level_values(i) for i in range(data.index.nlevels) + ] + else: + index_list = [Series(data.index, name=data.index.name)] else: index_list = [data[idx] for idx in com.convert_to_list_like(index)] diff --git a/pandas/tests/reshape/test_pivot_multilevel.py b/pandas/tests/reshape/test_pivot_multilevel.py index fbe299e8801db..308f7329b128f 100644 --- a/pandas/tests/reshape/test_pivot_multilevel.py +++ b/pandas/tests/reshape/test_pivot_multilevel.py @@ -228,3 +228,25 @@ def test_pivot_multiindexed_rows_and_cols(using_array_manager): expected = expected.astype("float64") tm.assert_frame_equal(res, expected) + + +def test_pivot_df_multiindex_index_none(): + # GH 23955 + df = pd.DataFrame( + [ + ["A", "A1", "label1", 1], + ["A", "A2", "label2", 2], + ["B", "A1", "label1", 3], + ["B", "A2", "label2", 4], + ], + columns=["index_1", "index_2", "label", "value"], + ) + df = df.set_index(["index_1", "index_2"]) + + result = df.pivot(index=None, columns="label", values="value") + expected = pd.DataFrame( + [[1.0, np.nan], [np.nan, 2.0], [3.0, np.nan], [np.nan, 4.0]], + index=df.index, + columns=Index(["label1", "label2"], name="label"), + ) + tm.assert_frame_equal(result, expected)