Skip to content

BUG: DataFrame.drop fails when columns argument given tuple #43985

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 3 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
12 changes: 10 additions & 2 deletions pandas/core/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,9 @@ def asarray_tuplesafe(values, dtype: NpDtype | None = None) -> np.ndarray:
return result


def index_labels_to_array(labels, dtype: NpDtype | None = None) -> np.ndarray:
def index_labels_to_array(
labels, dtype: NpDtype | None = None, ndim: int | None = None
) -> np.ndarray:
"""
Transform label or iterable of labels to array, for use in Index.

Expand All @@ -261,9 +263,15 @@ def index_labels_to_array(labels, dtype: NpDtype | None = None) -> np.ndarray:
-------
array
"""
if isinstance(labels, (str, tuple)):
if isinstance(labels, str):
labels = [labels]

if isinstance(labels, tuple):
if ndim == 1:
labels = list(labels)
else:
labels = [labels]

Copy link
Member

Choose a reason for hiding this comment

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

Would this change behavior for tuple column names?

Copy link
Member Author

Choose a reason for hiding this comment

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

Good point, fails indeed, added test for it, will try to resolve.

Copy link
Member

Choose a reason for hiding this comment

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

Not sure if it is resolvable - if you sometimes treat a tuple as a label and sometimes unpack as a list, seems like there would be unavoidable ambiguities? Would be more inclined to say the behavior is correct as is, but haven't thought about it too much

Copy link
Member Author

Choose a reason for hiding this comment

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

I see your point and there probably is some ambiguity since we can also use tuples to drop MultiIndex. I can revert the changes and just add a test that the described case always raises.

Copy link
Member

Choose a reason for hiding this comment

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

sounds great, thanks!

if not isinstance(labels, (list, np.ndarray)):
try:
labels = list(labels)
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -6448,7 +6448,7 @@ def drop(self, labels, errors: str_t = "raise") -> Index:
if not isinstance(labels, Index):
# avoid materializing e.g. RangeIndex
arr_dtype = "object" if self.dtype == "object" else None
labels = com.index_labels_to_array(labels, dtype=arr_dtype)
labels = com.index_labels_to_array(labels, dtype=arr_dtype, ndim=self.ndim)

indexer = self.get_indexer_for(labels)
mask = indexer == -1
Expand Down
14 changes: 14 additions & 0 deletions pandas/tests/frame/methods/test_drop.py
Original file line number Diff line number Diff line change
Expand Up @@ -546,3 +546,17 @@ def test_drop_level_missing_label_multiindex(self):
df = DataFrame(index=MultiIndex.from_product([range(3), range(3)]))
with pytest.raises(KeyError, match="labels \\[5\\] not found in level"):
df.drop(5, level=0)

def test_drop_labels_is_tuple(self):
# GH 43978
df = DataFrame(np.arange(12).reshape(3, 4), columns=["A", "B", "C", "D"])
result = df.drop(columns=("A", "B"))
expected = DataFrame({"C": [2, 6, 10], "D": [3, 7, 11]})
tm.assert_frame_equal(result, expected)

def test_drop_columns_are_tuple(self):
# GH 43978
df = DataFrame(np.arange(6).reshape(3, 2), columns=[("A", "B"), ("C", "D")])
result = df.drop(columns=("A", "B"))
expected = DataFrame([1, 3, 5], columns=[("C", "D")])
tm.assert_frame_equal(result, expected)