Skip to content

Commit ebe760e

Browse files
authored
BUG: DataFrame.drop raising TypeError for string label with non-unique MultiIndex and no level provided (#38220)
1 parent e91cbd7 commit ebe760e

File tree

3 files changed

+13
-1
lines changed

3 files changed

+13
-1
lines changed

doc/source/whatsnew/v1.3.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -211,7 +211,7 @@ Missing
211211
MultiIndex
212212
^^^^^^^^^^
213213

214-
-
214+
- Bug in :meth:`DataFrame.drop` raising ``TypeError`` when :class:`MultiIndex` is non-unique and no level is provided (:issue:`36293`)
215215
-
216216

217217
I/O

pandas/core/generic.py

+4
Original file line numberDiff line numberDiff line change
@@ -4182,6 +4182,10 @@ def _drop_axis(
41824182
# GH 18561 MultiIndex.drop should raise if label is absent
41834183
if errors == "raise" and indexer.all():
41844184
raise KeyError(f"{labels} not found in axis")
4185+
elif isinstance(axis, MultiIndex) and labels.dtype == "object":
4186+
# Set level to zero in case of MultiIndex and label is string,
4187+
# because isin can't handle strings for MultiIndexes GH#36293
4188+
indexer = ~axis.get_level_values(0).isin(labels)
41854189
else:
41864190
indexer = ~axis.isin(labels)
41874191
# Check if label doesn't exist along axis

pandas/tests/frame/methods/test_drop.py

+8
Original file line numberDiff line numberDiff line change
@@ -441,3 +441,11 @@ def test_inplace_drop_and_operation(self, operation, inplace):
441441
# Perform operation and check result
442442
getattr(y, operation)(1)
443443
tm.assert_frame_equal(df, expected)
444+
445+
def test_drop_with_non_unique_multiindex(self):
446+
# GH#36293
447+
mi = MultiIndex.from_arrays([["x", "y", "x"], ["i", "j", "i"]])
448+
df = DataFrame([1, 2, 3], index=mi)
449+
result = df.drop(index="x")
450+
expected = DataFrame([2], index=MultiIndex.from_arrays([["y"], ["j"]]))
451+
tm.assert_frame_equal(result, expected)

0 commit comments

Comments
 (0)