Skip to content

BUG: DataFrame.pivot(index=None) with MultiIndex #45141

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 31, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.4.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
^^^^^^
Expand Down
8 changes: 7 additions & 1 deletion pandas/core/reshape/pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)]

Expand Down
22 changes: 22 additions & 0 deletions pandas/tests/reshape/test_pivot_multilevel.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)