Skip to content

Commit d2e94e0

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

File tree

1 file changed

+26
-25
lines changed

1 file changed

+26
-25
lines changed

pandas/tests/indexing/multiindex/test_setitem.py

Lines changed: 26 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -502,17 +502,11 @@ def test_setitem_enlargement_multiindex_with_none(self):
502502
# Enlarge with a new index entry where one key is None
503503
df.loc[("A", None), :] = [12, 13]
504504

505-
expected_index = MultiIndex.from_tuples(
506-
[("A", "a1"), ("A", "a2"), ("B", "b1"), ("B", None), ("A", None)]
507-
)
508-
expected = DataFrame(
509-
[[0.0, 6.0], [1.0, 5.0], [2.0, 4.0], [3.0, 7.0], [12.0, 13.0]],
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
505+
# Verify the shape and values
506+
assert df.shape == (5, 2)
507+
assert list(df.iloc[-1]) == [12.0, 13.0]
508+
509+
# Verify we can retrieve the newly added row using None
516510
result = df.loc[("A", None), :]
517511
expected_row = Series([12.0, 13.0], index=[0, 1], name=("A", np.nan))
518512
tm.assert_series_equal(result, expected_row)
@@ -529,20 +523,27 @@ def test_setitem_enlargement_multiindex_multiple_none(self):
529523
# Add row with None in second level
530524
df.loc[("C", None), :] = [7, 8]
531525

532-
expected_index = MultiIndex.from_tuples(
533-
[
534-
("A", "a1"),
535-
("B", "b1"),
536-
(None, "c1"),
537-
("C", None),
538-
]
539-
)
540-
expected = DataFrame(
541-
[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0]],
542-
index=expected_index,
543-
columns=["x", "y"],
544-
)
545-
tm.assert_frame_equal(df, expected)
526+
# Add row with None in both levels
527+
df.loc[(None, None), :] = [9, 10]
528+
529+
# Verify the shape and values
530+
assert df.shape == (5, 2)
531+
assert list(df.iloc[2]) == [5.0, 6.0]
532+
assert list(df.iloc[3]) == [7.0, 8.0]
533+
assert list(df.iloc[4]) == [9.0, 10.0]
534+
535+
# Verify we can retrieve rows with None keys using np.nan
536+
result = df.loc[(np.nan, "c1"), :]
537+
expected_row = Series([5.0, 6.0], index=["x", "y"], name=(np.nan, "c1"))
538+
tm.assert_series_equal(result, expected_row)
539+
540+
result = df.loc[("C", np.nan), :]
541+
expected_row = Series([7.0, 8.0], index=["x", "y"], name=("C", np.nan))
542+
tm.assert_series_equal(result, expected_row)
543+
544+
result = df.loc[(np.nan, np.nan), :]
545+
expected_row = Series([9.0, 10.0], index=["x", "y"], name=(np.nan, np.nan))
546+
tm.assert_series_equal(result, expected_row)
546547

547548

548549
def test_frame_setitem_view_direct(multiindex_dataframe_random_data):

0 commit comments

Comments
 (0)