Skip to content

Commit ac60759

Browse files
phoflmeeseeksmachine
authored andcommitted
Backport PR pandas-dev#48178: REGR: loc not working with NamedTuple
1 parent 2f71a9c commit ac60759

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
@@ -19,6 +19,7 @@ Fixed regressions
1919
- Fixed regression in calling bitwise numpy ufuncs (for example, ``np.bitwise_and``) on Index objects (:issue:`46769`)
2020
- Fixed regression in :func:`cut` using a ``datetime64`` IntervalIndex as bins (:issue:`46218`)
2121
- Fixed regression in :meth:`DataFrame.select_dtypes` where ``include="number"`` included :class:`BooleanDtype` (:issue:`46870`)
22+
- Fixed regression in :meth:`DataFrame.loc` raising error when indexing with a ``NamedTuple`` (:issue:`48124`)
2223
- Fixed regression in :meth:`DataFrame.loc` not updating the cache correctly after values were set (:issue:`47867`)
2324
- Fixed regression in :meth:`DataFrame.loc` not aligning index in some cases when setting a :class:`DataFrame` (:issue:`47578`)
2425
- 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
@@ -1175,6 +1175,9 @@ def _getitem_axis(self, key, axis: int):
11751175

11761176
labels = self.obj._get_axis(axis)
11771177

1178+
if isinstance(key, tuple) and isinstance(labels, MultiIndex):
1179+
key = tuple(key)
1180+
11781181
if isinstance(key, slice):
11791182
self._validate_key(key, axis)
11801183
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,
@@ -1339,6 +1340,23 @@ def test_loc_setitem_rhs_frame(self, idxr, val):
13391340
expected = DataFrame({"a": [np.nan, val]})
13401341
tm.assert_frame_equal(df, expected)
13411342

1343+
def test_loc_named_tuple_for_midx(self):
1344+
# GH#48124
1345+
df = DataFrame(
1346+
index=MultiIndex.from_product(
1347+
[["A", "B"], ["a", "b", "c"]], names=["first", "second"]
1348+
)
1349+
)
1350+
indexer_tuple = namedtuple("Indexer", df.index.names)
1351+
idxr = indexer_tuple(first="A", second=["a", "b"])
1352+
result = df.loc[idxr, :]
1353+
expected = DataFrame(
1354+
index=MultiIndex.from_tuples(
1355+
[("A", "a"), ("A", "b")], names=["first", "second"]
1356+
)
1357+
)
1358+
tm.assert_frame_equal(result, expected)
1359+
13421360

13431361
class TestDataFrameIndexingUInt64:
13441362
def test_setitem(self, uint64_frame):

0 commit comments

Comments
 (0)