Skip to content

BUG: cast to correct dtype in Index.drop() #18309

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

Merged
merged 3 commits into from
Dec 29, 2017
Merged
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.23.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,7 @@ Indexing
- Bug in :func:`MultiIndex.remove_unused_levels` which would fill nan values (:issue:`18417`)
- Bug in :func:`MultiIndex.from_tuples`` which would fail to take zipped tuples in python3 (:issue:`18434`)
- Bug in :class:`Index` construction from list of mixed type tuples (:issue:`18505`)
- Bug in :func:`Index.drop` when passing a list of both tuples and non-tuples (:issue:`18304`)
- Bug in :class:`IntervalIndex` where empty and purely NA data was constructed inconsistently depending on the construction method (:issue:`18421`)
- Bug in :func:`IntervalIndex.symmetric_difference` where the symmetric difference with a non-``IntervalIndex`` did not raise (:issue:`18475`)
- Bug in indexing a datetimelike ``Index`` that raised ``ValueError`` instead of ``IndexError`` (:issue:`18386`).
Expand Down
16 changes: 14 additions & 2 deletions pandas/core/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -398,7 +398,19 @@ def _asarray_tuplesafe(values, dtype=None):
return result


def _index_labels_to_array(labels):
def _index_labels_to_array(labels, dtype=None):
Copy link
Contributor

Choose a reason for hiding this comment

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

doc-string here would be nice; in theory some unit tests if you can.

Copy link
Member Author

Choose a reason for hiding this comment

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

docstring added; this is tested in my new test and, in old tests, whenever Index(dtype='object').drop() is called.

Copy link
Contributor

Choose a reason for hiding this comment

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

I am asking for some unit-tests for this routine itself. all of these helper routines should ideally have tests.

Copy link
Member Author

Choose a reason for hiding this comment

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

Uhm... unless there are specific coverage (lines of code) issues, I personally don't see this as an efficient use of my time, considering how many and how frequently changed are pandas internal routines.

"""
Transform label or iterable of labels to array, for use in Index.

Parameters
----------
dtype : dtype
If specified, use as dtype of the resulting array, otherwise infer.

Returns
-------
array
"""
if isinstance(labels, (compat.string_types, tuple)):
labels = [labels]

Expand All @@ -408,7 +420,7 @@ def _index_labels_to_array(labels):
except TypeError: # non-iterable
labels = [labels]

labels = _asarray_tuplesafe(labels)
labels = _asarray_tuplesafe(labels, dtype=dtype)

return labels

Expand Down
3 changes: 2 additions & 1 deletion pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3761,7 +3761,8 @@ def drop(self, labels, errors='raise'):
-------
dropped : Index
"""
labels = _index_labels_to_array(labels)
arr_dtype = 'object' if self.dtype == 'object' else None
labels = _index_labels_to_array(labels, dtype=arr_dtype)
indexer = self.get_indexer(labels)
mask = indexer == -1
if mask.any():
Expand Down
21 changes: 21 additions & 0 deletions pandas/tests/indexes/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1429,6 +1429,27 @@ def test_drop(self):
expected = Index([1, 2])
tm.assert_index_equal(dropped, expected)

@pytest.mark.parametrize("values", [['a', 'b', ('c', 'd')],
['a', ('c', 'd'), 'b'],
[('c', 'd'), 'a', 'b']])
@pytest.mark.parametrize("to_drop", [[('c', 'd'), 'a'], ['a', ('c', 'd')]])
def test_drop_tuple(self, values, to_drop):
# GH 18304
index = pd.Index(values)
expected = pd.Index(['b'])

result = index.drop(to_drop)
tm.assert_index_equal(result, expected)

removed = index.drop(to_drop[0])
for drop_me in to_drop[1], [to_drop[1]]:
result = removed.drop(drop_me)
tm.assert_index_equal(result, expected)

removed = index.drop(to_drop[1])
for drop_me in to_drop[1], [to_drop[1]]:
pytest.raises(ValueError, removed.drop, drop_me)

def test_tuple_union_bug(self):
import pandas
import numpy as np
Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/reshape/test_pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -1631,3 +1631,15 @@ def test_crosstab_dup_index_names(self):
index=expected_index,
columns=expected_index)
tm.assert_frame_equal(result, expected)

@pytest.mark.parametrize("names", [['a', ('b', 'c')],
[('a', 'b'), 'c']])
def test_crosstab_tuple_name(self, names):
s1 = pd.Series(range(3), name=names[0])
s2 = pd.Series(range(1, 4), name=names[1])

mi = pd.MultiIndex.from_arrays([range(3), range(1, 4)], names=names)
expected = pd.Series(1, index=mi).unstack(1, fill_value=0)

result = pd.crosstab(s1, s2)
tm.assert_frame_equal(result, expected)