@@ -492,14 +492,13 @@ def test_setitem_enlargement_keep_index_names(self):
492492
493493 def test_setitem_enlargement_with_none_key (self ):
494494 # GH#59153
495- # Test that enlarging a MultiIndex DataFrame works when one or more
496- # level keys are None
495+ # Test basic enlargement with None keys in different levels
497496 index = MultiIndex .from_tuples (
498497 [("A" , "a1" ), ("A" , "a2" ), ("B" , "b1" ), ("B" , None )]
499498 )
500499 df = DataFrame ([(0 , 6 ), (1 , 5 ), (2 , 4 ), (3 , 7 )], index = index )
501500
502- # Test 1: Enlarge with a new index entry where second key is None
501+ # Enlarge with None in second level
503502 df .loc [("A" , None ), :] = [12 , 13 ]
504503 expected_index = MultiIndex .from_tuples (
505504 [
@@ -516,7 +515,7 @@ def test_setitem_enlargement_with_none_key(self):
516515 )
517516 tm .assert_frame_equal (df , expected )
518517
519- # Test 2: Enlarge with None in first level key
518+ # Enlarge with None in first level
520519 df .loc [(None , "c1" ), :] = [14 , 15 ]
521520 expected_index = MultiIndex .from_tuples (
522521 [
@@ -534,6 +533,45 @@ def test_setitem_enlargement_with_none_key(self):
534533 )
535534 tm .assert_frame_equal (df , expected )
536535
536+ def test_setitem_enlargement_none_key_indexslice_retrieval (self ):
537+ # GH#59153
538+ # Test IndexSlice functionality and retrieval with None keys
539+
540+ # Test IndexSlice selection with None
541+ idx = pd .IndexSlice
542+ df = DataFrame (
543+ [[10 ], [20 ], [30 ]],
544+ index = MultiIndex .from_tuples ([("A" , "a1" ), ("B" , None ), ("C" , "c1" )]),
545+ columns = ["val" ]
546+ )
547+
548+ result = df .loc [idx [:, None ], :]
549+ expected = DataFrame ([[20 ]], index = MultiIndex .from_tuples ([("B" , None )]), columns = ["val" ])
550+ tm .assert_frame_equal (result , expected )
551+
552+ # Enlarge using IndexSlice with None
553+ df .loc [idx ["D" , None ], :] = [40 ]
554+ assert df .loc [("D" , None ), "val" ] == 40
555+
556+ # Test retrieval after enlargement
557+ df2 = DataFrame (
558+ [[100 , 200 ]],
559+ index = MultiIndex .from_tuples ([("A" , "a1" )]),
560+ columns = ["col1" , "col2" ]
561+ )
562+
563+ df2 .loc [("A" , None ), :] = [300 , 400 ]
564+
565+ # Retrieve using full tuple key
566+ result = df2 .loc [("A" , None ), :]
567+ expected = Series ([300 , 400 ], index = ["col1" , "col2" ], name = ("A" , None ))
568+ tm .assert_series_equal (result , expected )
569+
570+ # Retrieve using xs
571+ result_xs = df2 .xs ("A" )
572+ assert None in result_xs .index
573+ assert result_xs .loc [None , "col1" ] == 300
574+
537575
538576def test_frame_setitem_view_direct (multiindex_dataframe_random_data ):
539577 # this works because we are modifying the underlying array
0 commit comments