Skip to content

BUG: Fix keyerror bug when indexing multiindex columns with NaT values #60463

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 3 commits into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
7 changes: 3 additions & 4 deletions pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -4084,11 +4084,10 @@ def insert(self, loc: int, item) -> MultiIndex:
# have to insert into level
# must insert at end otherwise you have to recompute all the
# other codes
if isna(k): # GH 59003
lev_loc = len(level)
level = level.insert(lev_loc, k)
if isna(level[lev_loc]): # GH 59003, 60388
lev_loc = -1
else:
lev_loc = len(level)
level = level.insert(lev_loc, k)
else:
lev_loc = level.get_loc(k)

Expand Down
21 changes: 21 additions & 0 deletions pandas/tests/frame/methods/test_reset_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,27 @@ def test_reset_index_datetime3(self, tz_naive_fixture):
result = df.reset_index()
tm.assert_frame_equal(result, expected)

def test_reset_index_multiindex_dt_with_nan(self):
# GH#60388
df = DataFrame(
{
"Date": [
datetime(2024, 11, 1),
datetime(2024, 11, 1),
datetime(2024, 11, 2),
datetime(2024, 11, 2),
],
"sub": ["a", "b", "c", "d"],
"value1": [1, 2, 3, 4],
"value2": [5, 6, 7, 8],
}
)
df = df.pivot(index="sub", columns="Date", values=["value1", "value2"])
df = df.reset_index()
result = df[df.columns[0]]
expected = Series(["a", "b", "c", "d"], name=("sub", np.nan))
tm.assert_series_equal(result, expected)

def test_reset_index_period(self):
# GH#7746
idx = MultiIndex.from_product(
Expand Down
Loading