Skip to content

BUG: fix Frame getitem when column keys are nested tuples #43939

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/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,8 @@ def asarray_tuplesafe(values, dtype: NpDtype | None = None) -> np.ndarray:
if issubclass(result.dtype.type, str):
result = np.asarray(values, dtype=object)

if result.ndim == 2:
# For ndim > 2 distinguish between nested tuples and multidimensional arrays
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why are these coerced to in the first place? we need to stop that from happening

if result.ndim == 2 or (result.ndim > 2 and isinstance(values[0][0], tuple)):
# Avoid building an array of arrays:
values = [tuple(x) for x in values]
result = construct_1d_object_array_from_listlike(values)
Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/frame/indexing/test_getitem.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,15 @@ def test_getitem_iloc_two_dimensional_generator(self):
expected = Series([5, 6], name="b", index=[1, 2])
tm.assert_series_equal(result, expected)

def test_getitem_key_nested_tuple(self):
# GH 43780
df = DataFrame([[0, 0]], columns=Index([(("a",), (1,)), (("b",), (2,))]))
key_list = [df.columns[0]]
result = df[key_list]

expected = DataFrame([0], columns=Index(key_list))
tm.assert_frame_equal(result, expected)


class TestGetitemCallable:
def test_getitem_callable(self, float_frame):
Expand Down