Skip to content

Commit 53d3c45

Browse files
authored
REGR: loc not working with NamedTuple (#48178)
1 parent ae291e9 commit 53d3c45

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
@@ -20,6 +20,7 @@ Fixed regressions
2020
- Fixed regression in calling bitwise numpy ufuncs (for example, ``np.bitwise_and``) on Index objects (:issue:`46769`)
2121
- Fixed regression in :func:`cut` using a ``datetime64`` IntervalIndex as bins (:issue:`46218`)
2222
- Fixed regression in :meth:`DataFrame.select_dtypes` where ``include="number"`` included :class:`BooleanDtype` (:issue:`46870`)
23+
- Fixed regression in :meth:`DataFrame.loc` raising error when indexing with a ``NamedTuple`` (:issue:`48124`)
2324
- Fixed regression in :meth:`DataFrame.loc` not updating the cache correctly after values were set (:issue:`47867`)
2425
- Fixed regression in :meth:`DataFrame.loc` not aligning index in some cases when setting a :class:`DataFrame` (:issue:`47578`)
2526
- Fixed regression in :meth:`DataFrame.loc` setting a length-1 array like value to a single value in the DataFrame (:issue:`46268`)

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,
@@ -1386,6 +1387,23 @@ def test_iloc_setitem_ea_null_slice_length_one_list(self, func):
13861387
expected = DataFrame({"a": [5, 5, 5]}, dtype="Int64")
13871388
tm.assert_frame_equal(df, expected)
13881389

1390+
def test_loc_named_tuple_for_midx(self):
1391+
# GH#48124
1392+
df = DataFrame(
1393+
index=MultiIndex.from_product(
1394+
[["A", "B"], ["a", "b", "c"]], names=["first", "second"]
1395+
)
1396+
)
1397+
indexer_tuple = namedtuple("Indexer", df.index.names)
1398+
idxr = indexer_tuple(first="A", second=["a", "b"])
1399+
result = df.loc[idxr, :]
1400+
expected = DataFrame(
1401+
index=MultiIndex.from_tuples(
1402+
[("A", "a"), ("A", "b")], names=["first", "second"]
1403+
)
1404+
)
1405+
tm.assert_frame_equal(result, expected)
1406+
13891407

13901408
class TestDataFrameIndexingUInt64:
13911409
def test_setitem(self, uint64_frame):

0 commit comments

Comments
 (0)