Skip to content

Commit a2a939e

Browse files
committed
REGR: loc not working with NamedTuple
1 parent ae47909 commit a2a939e

File tree

3 files changed

+22
-0
lines changed

3 files changed

+22
-0
lines changed

doc/source/whatsnew/v1.4.4.rst

+1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ including other versions of pandas.
1515
Fixed regressions
1616
~~~~~~~~~~~~~~~~~
1717
- Fixed regression in taking NULL :class:`objects` from a :class:`DataFrame` causing a segmentation violation. These NULL values are created by :meth:`numpy.empty_like` (:issue:`46848`)
18+
- Fixed regression in :meth:`DataFrame.loc` raising error when indexing with a ``NamedTuple`` (:issue:`48124`)
1819
- Fixed regression in :func:`concat` materializing :class:`Index` during sorting even if :class:`Index` was already sorted (:issue:`47501`)
1920
- Fixed regression in :func:`cut` using a ``datetime64`` IntervalIndex as bins (:issue:`46218`)
2021
- Fixed regression in :meth:`DataFrame.select_dtypes` where ``include="number"`` included :class:`BooleanDtype` (:issue:`46870`)

pandas/core/indexing.py

+3
Original file line numberDiff line numberDiff line change
@@ -1283,6 +1283,9 @@ def _getitem_axis(self, key, axis: int):
12831283

12841284
labels = self.obj._get_axis(axis)
12851285

1286+
if isinstance(key, tuple) and isinstance(labels, MultiIndex):
1287+
key = tuple(key)
1288+
12861289
if isinstance(key, slice):
12871290
self._validate_key(key, axis)
12881291
return self._get_slice_axis(key, axis=axis)

pandas/tests/frame/indexing/test_indexing.py

+18
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from collections import namedtuple
12
from datetime import (
23
datetime,
34
timedelta,
@@ -1371,6 +1372,23 @@ def test_iloc_setitem_ea_null_slice_length_one_list(self, func):
13711372
expected = DataFrame({"a": [5, 5, 5]}, dtype="Int64")
13721373
tm.assert_frame_equal(df, expected)
13731374

1375+
def test_loc_named_tuple_for_midx(self):
1376+
# GH#48124
1377+
df = DataFrame(
1378+
index=MultiIndex.from_product(
1379+
[["A", "B"], ["a", "b", "c"]], names=["first", "second"]
1380+
)
1381+
)
1382+
indexer_tuple = namedtuple("Indexer", df.index.names)
1383+
idxr = indexer_tuple(first="A", second=["a", "b"])
1384+
result = df.loc[idxr, :]
1385+
expected = DataFrame(
1386+
index=MultiIndex.from_tuples(
1387+
[("A", "a"), ("A", "b")], names=["first", "second"]
1388+
)
1389+
)
1390+
tm.assert_frame_equal(result, expected)
1391+
13741392

13751393
class TestDataFrameIndexingUInt64:
13761394
def test_setitem(self, uint64_frame):

0 commit comments

Comments
 (0)