Skip to content

Commit b026334

Browse files
committed
Fix insertion of None value in MultiIndex
1 parent a4c9446 commit b026334

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

pandas/core/indexes/multi.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -3906,8 +3906,11 @@ def insert(self, loc: int, item) -> MultiIndex:
39063906
# have to insert into level
39073907
# must insert at end otherwise you have to recompute all the
39083908
# other codes
3909-
lev_loc = len(level)
3910-
level = level.insert(lev_loc, k)
3909+
if k is None: # GH 59003
3910+
lev_loc = -1
3911+
else:
3912+
lev_loc = len(level)
3913+
level = level.insert(lev_loc, k)
39113914
else:
39123915
lev_loc = level.get_loc(k)
39133916

pandas/tests/test_multilevel.py

+9
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import pandas as pd
77
from pandas import (
88
DataFrame,
9+
Index,
910
MultiIndex,
1011
Series,
1112
)
@@ -288,6 +289,14 @@ def test_multiindex_with_na(self):
288289

289290
tm.assert_frame_equal(df, expected)
290291

292+
def test_multiindex_insert_level_with_na(self):
293+
# GH 59003
294+
indices = [["one"], ["a"], ["yes"]]
295+
df = DataFrame([0], index=indices).T
296+
df["one", None, "yes"] = 1
297+
expected = DataFrame([1], index=Index(["yes"])).T
298+
tm.assert_frame_equal(df["one"][None], expected)
299+
291300

292301
class TestSorted:
293302
"""everything you wanted to test about sorting"""

0 commit comments

Comments
 (0)