Skip to content

Commit cce02e4

Browse files
author
wdyy20041223
committed
TST: Add regression tests for enlarging MultiIndex with None keys (GH#59153)
1 parent 88c276a commit cce02e4

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

pandas/tests/indexing/multiindex/test_setitem.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -490,6 +490,64 @@ def test_setitem_enlargement_keep_index_names(self):
490490
)
491491
tm.assert_frame_equal(df, expected)
492492

493+
def test_setitem_enlargement_multiindex_with_none(self):
494+
# GH#59153
495+
# Test that we can enlarge a DataFrame with a MultiIndex
496+
# when one or more level keys are None
497+
index = MultiIndex.from_tuples(
498+
[("A", "a1"), ("A", "a2"), ("B", "b1"), ("B", None)]
499+
)
500+
df = DataFrame([(0, 6), (1, 5), (2, 4), (3, 7)], index=index)
501+
502+
# Enlarge with a new index entry where one key is None
503+
df.loc[("A", None), :] = [12, 13]
504+
505+
expected_index = MultiIndex.from_tuples(
506+
[("A", "a1"), ("A", "a2"), ("B", "b1"), ("B", None), ("A", None)]
507+
)
508+
expected = DataFrame(
509+
[[0, 6], [1, 5], [2, 4], [3, 7], [12, 13]],
510+
index=expected_index,
511+
columns=[0, 1],
512+
)
513+
tm.assert_frame_equal(df, expected)
514+
515+
# Test retrieval of the newly added row
516+
result = df.loc[("A", None), :]
517+
expected_row = Series([12, 13], index=[0, 1], name=("A", np.nan))
518+
tm.assert_series_equal(result, expected_row)
519+
520+
def test_setitem_enlargement_multiindex_multiple_none(self):
521+
# GH#59153
522+
# Test enlarging with multiple None keys in different levels
523+
index = MultiIndex.from_tuples([("A", "a1"), ("B", "b1")])
524+
df = DataFrame([[1, 2], [3, 4]], index=index, columns=["x", "y"])
525+
526+
# Add row with None in first level
527+
df.loc[(None, "c1"), :] = [5, 6]
528+
529+
# Add row with None in second level
530+
df.loc[("C", None), :] = [7, 8]
531+
532+
# Add row with None in both levels
533+
df.loc[(None, None), :] = [9, 10]
534+
535+
expected_index = MultiIndex.from_tuples(
536+
[
537+
("A", "a1"),
538+
("B", "b1"),
539+
(None, "c1"),
540+
("C", None),
541+
(None, None),
542+
]
543+
)
544+
expected = DataFrame(
545+
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]],
546+
index=expected_index,
547+
columns=["x", "y"],
548+
)
549+
tm.assert_frame_equal(df, expected)
550+
493551

494552
def test_frame_setitem_view_direct(multiindex_dataframe_random_data):
495553
# this works because we are modifying the underlying array

0 commit comments

Comments
 (0)