Skip to content

Commit d604aa8

Browse files
chaoyihumroeschke
andauthored
Fix insertion of None value in MultiIndex (#59069)
* Fix insertion of None value in MultiIndex * add whatnew entry * check for NA values using missing::isna * adding test insertion of np.nan * update whatsnew entry * test case revision --------- Co-authored-by: Matthew Roeschke <[email protected]>
1 parent a3d5e00 commit d604aa8

File tree

3 files changed

+13
-2
lines changed

3 files changed

+13
-2
lines changed

doc/source/whatsnew/v3.0.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -545,6 +545,7 @@ MultiIndex
545545
^^^^^^^^^^
546546
- :func:`DataFrame.loc` with ``axis=0`` and :class:`MultiIndex` when setting a value adds extra columns (:issue:`58116`)
547547
- :meth:`DataFrame.melt` would not accept multiple names in ``var_name`` when the columns were a :class:`MultiIndex` (:issue:`58033`)
548+
- :meth:`MultiIndex.insert` would not insert NA value correctly at unified location of index -1 (:issue:`59003`)
548549
-
549550

550551
I/O

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 isna(k): # 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

+7
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,13 @@ def test_multiindex_with_na(self):
288288

289289
tm.assert_frame_equal(df, expected)
290290

291+
@pytest.mark.parametrize("na", [None, np.nan])
292+
def test_multiindex_insert_level_with_na(self, na):
293+
# GH 59003
294+
df = DataFrame([0], columns=[["A"], ["B"]])
295+
df[na, "B"] = 1
296+
tm.assert_frame_equal(df[na], DataFrame([1], columns=["B"]))
297+
291298

292299
class TestSorted:
293300
"""everything you wanted to test about sorting"""

0 commit comments

Comments
 (0)