Skip to content

Commit bbd0f66

Browse files
authored
BUG: loc dropping levels when df has only one row (#38150)
1 parent 52112d1 commit bbd0f66

File tree

3 files changed

+21
-3
lines changed

3 files changed

+21
-3
lines changed

doc/source/whatsnew/v1.3.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,7 @@ Indexing
234234
- Bug in :meth:`CategoricalIndex.get_indexer` failing to raise ``InvalidIndexError`` when non-unique (:issue:`38372`)
235235
- Bug in inserting many new columns into a :class:`DataFrame` causing incorrect subsequent indexing behavior (:issue:`38380`)
236236
- Bug in :meth:`DataFrame.iloc.__setitem__` and :meth:`DataFrame.loc.__setitem__` with mixed dtypes when setting with a dictionary value (:issue:`38335`)
237-
-
237+
- Bug in :meth:`DataFrame.loc` dropping levels of :class:`MultiIndex` when :class:`DataFrame` used as input has only one row (:issue:`10521`)
238238
-
239239

240240
Missing

pandas/core/indexing.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -842,8 +842,12 @@ def _getitem_nested_tuple(self, tup: Tuple):
842842
if self.name != "loc":
843843
# This should never be reached, but lets be explicit about it
844844
raise ValueError("Too many indices")
845-
with suppress(IndexingError):
846-
return self._handle_lowerdim_multi_index_axis0(tup)
845+
if self.ndim == 1 or not any(isinstance(x, slice) for x in tup):
846+
# GH#10521 Series should reduce MultiIndex dimensions instead of
847+
# DataFrame, IndexingError is not raised when slice(None,None,None)
848+
# with one row.
849+
with suppress(IndexingError):
850+
return self._handle_lowerdim_multi_index_axis0(tup)
847851

848852
# this is a series with a multi-index specified a tuple of
849853
# selectors

pandas/tests/indexing/multiindex/test_loc.py

+14
Original file line numberDiff line numberDiff line change
@@ -695,3 +695,17 @@ def test_loc_getitem_index_differently_ordered_slice_none():
695695
columns=["a", "b"],
696696
)
697697
tm.assert_frame_equal(result, expected)
698+
699+
700+
def test_loc_getitem_drops_levels_for_one_row_dataframe():
701+
# GH#10521
702+
mi = MultiIndex.from_arrays([["x"], ["y"], ["z"]], names=["a", "b", "c"])
703+
df = DataFrame({"d": [0]}, index=mi)
704+
expected = df.copy()
705+
result = df.loc["x", :, "z"]
706+
tm.assert_frame_equal(result, expected)
707+
708+
ser = Series([0], index=mi)
709+
result = ser.loc["x", :, "z"]
710+
expected = Series([0], index=Index(["y"], name="b"))
711+
tm.assert_series_equal(result, expected)

0 commit comments

Comments
 (0)