Skip to content

implement searchsorted for multindex (bug #14833) #23210

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
8 changes: 8 additions & 0 deletions pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# pylint: disable=E1101,E1103,W0232
import datetime
import warnings
from functools import reduce
from sys import getsizeof

import numpy as np
Expand Down Expand Up @@ -2899,6 +2900,13 @@ def isin(self, values, level=None):
else:
return np.lib.arraysetops.in1d(labs, sought_labels)

def searchsorted(self, arr):
dtype = [l.dtype.descr for l in self.levels]
Copy link
Contributor

Choose a reason for hiding this comment

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

this will be much more performant to do this level by level (as you iterate over the key). which btw must be fully specified. needs a doc-string and error checking.

dtype = reduce(lambda x, y: x + y, dtype, [])
arr = np.asarray(arr, dtype=dtype)
values = self.values.astype(dtype)
return values.searchsorted(arr)


MultiIndex._add_numeric_methods_disabled()
MultiIndex._add_numeric_methods_add_sub_disabled()
Expand Down
5 changes: 5 additions & 0 deletions pandas/tests/indexes/multi/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -346,3 +346,8 @@ def test_get_indexer_categorical_time():
Categorical(date_range("2012-01-01", periods=3, freq='H'))])
result = midx.get_indexer(midx)
tm.assert_numpy_array_equal(result, np.arange(9, dtype=np.intp))


Copy link
Contributor

Choose a reason for hiding this comment

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

needs error checking, and a full-on test where the element is there (to be honest you should simply do a .get_loc()) first to find it then if not found do the searchsorted. You must also assert that the index is lexsorted as well.

def test_searchsorted():
i = MultiIndex.from_tuples([('a', 0), ('b', 1)]).searchsorted(('b', 0))
assert i == 1