Skip to content

Fixed BUG: Using NamedTuples with .iloc fails #48188 #57287

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion pandas/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1162,7 +1162,8 @@ def _check_deprecated_callable_usage(self, key: Any, maybe_callable: T) -> T:
@final
def __getitem__(self, key):
check_dict_or_set_indexers(key)
if type(key) is tuple:
##if type(key) is tuple:
if isinstance(key, tuple):
key = tuple(list(x) if is_iterator(x) else x for x in key)
key = tuple(com.apply_if_callable(x, self.obj) for x in key)
if self._is_scalar_access(key):
Expand Down
25 changes: 25 additions & 0 deletions pandas/tests/indexing/test_iloc.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@
import numpy as np
import pytest


import pandas as pd
from collections import namedtuple

from pandas.errors import IndexingError

from pandas import (
Expand Down Expand Up @@ -1463,3 +1467,24 @@ def test_iloc_nullable_int64_size_1_nan(self):
result.loc[:, "b"] = result.loc[:, "b"].astype("Int64")
expected = DataFrame({"a": ["test"], "b": array([NA], dtype="Int64")})
tm.assert_frame_equal(result, expected)



def test_iloc_with_namedtuple():
# setup a dataFrame
df = pd.DataFrame(np.arange(100).reshape(10, 10))

# define a namedtuple
Indexer = namedtuple("Indexer", ["row", "col"])

# Test .iloc with a regular tuple
result_with_tuple = df.iloc[(1, 2)]
assert result_with_tuple == df.iloc[1, 2]

# Test .iloc with a namedtuple
indexer = Indexer(row=1, col=2)
result_with_namedtuple = df.iloc[indexer]
assert result_with_namedtuple == df.iloc[1, 2]

# ensure both methods yield the same result testing the initial issue
assert result_with_tuple == result_with_namedtuple