Skip to content

Commit 7614bf3

Browse files
committed
BUG: cast to correct dtype in Index.drop()
closes #18304
1 parent 9c799e2 commit 7614bf3

File tree

4 files changed

+26
-3
lines changed

4 files changed

+26
-3
lines changed

doc/source/whatsnew/v0.22.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ Indexing
103103

104104
- Bug in :func:`Series.truncate` which raises ``TypeError`` with a monotonic ``PeriodIndex`` (:issue:`17717`)
105105
- Bug in :func:`DataFrame.groupby` where tuples were interpreted as lists of keys rather than as keys (:issue:`17979`, :issue:`18249`)
106+
- Bug in :func:`Index.drop` when passing a list of both tuples and non-tuples (:issue:`18304`)
106107
-
107108
-
108109

pandas/core/common.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -404,7 +404,7 @@ def _asarray_tuplesafe(values, dtype=None):
404404
return result
405405

406406

407-
def _index_labels_to_array(labels):
407+
def _index_labels_to_array(labels, dtype=None):
408408
if isinstance(labels, (compat.string_types, tuple)):
409409
labels = [labels]
410410

@@ -414,7 +414,7 @@ def _index_labels_to_array(labels):
414414
except TypeError: # non-iterable
415415
labels = [labels]
416416

417-
labels = _asarray_tuplesafe(labels)
417+
labels = _asarray_tuplesafe(labels, dtype=dtype)
418418

419419
return labels
420420

pandas/core/indexes/base.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -3747,7 +3747,8 @@ def drop(self, labels, errors='raise'):
37473747
-------
37483748
dropped : Index
37493749
"""
3750-
labels = _index_labels_to_array(labels)
3750+
arr_dtype = 'object' if self.dtype == 'object' else None
3751+
labels = _index_labels_to_array(labels, dtype=arr_dtype)
37513752
indexer = self.get_indexer(labels)
37523753
mask = indexer == -1
37533754
if mask.any():

pandas/tests/indexes/test_base.py

+21
Original file line numberDiff line numberDiff line change
@@ -1341,6 +1341,27 @@ def test_drop(self):
13411341
expected = Index([1, 2])
13421342
tm.assert_index_equal(dropped, expected)
13431343

1344+
@pytest.mark.parametrize("values", [['a', 'b', ('c', 'd')],
1345+
['a', ('c', 'd'), 'b'],
1346+
[('c', 'd'), 'a', 'b']])
1347+
@pytest.mark.parametrize("to_drop", [[('c', 'd'), 'a'], ['a', ('c', 'd')]])
1348+
def test_drop_tuple(self, values, to_drop):
1349+
# GH 18304
1350+
index = pd.Index(values)
1351+
expected = pd.Index(['b'])
1352+
1353+
result = index.drop(to_drop)
1354+
tm.assert_index_equal(result, expected)
1355+
1356+
removed = index.drop(to_drop[0])
1357+
for drop_me in to_drop[1], [to_drop[1]]:
1358+
result = removed.drop(drop_me)
1359+
tm.assert_index_equal(result, expected)
1360+
1361+
removed = index.drop(to_drop[1])
1362+
for drop_me in to_drop[1], [to_drop[1]]:
1363+
pytest.raises(ValueError, removed.drop, drop_me)
1364+
13441365
def test_tuple_union_bug(self):
13451366
import pandas
13461367
import numpy as np

0 commit comments

Comments
 (0)