Skip to content

Commit 60fe82c

Browse files
bourbakijreback
authored andcommitted
PERF: GH2003 Series.isin for categorical dtypes (#20522)
1 parent 7ec74e5 commit 60fe82c

File tree

7 files changed

+109
-2
lines changed

7 files changed

+109
-2
lines changed

asv_bench/benchmarks/categoricals.py

+21
Original file line numberDiff line numberDiff line change
@@ -148,3 +148,24 @@ def time_rank_int_cat(self):
148148

149149
def time_rank_int_cat_ordered(self):
150150
self.s_int_cat_ordered.rank()
151+
152+
153+
class Isin(object):
154+
155+
goal_time = 0.2
156+
157+
params = ['object', 'int64']
158+
param_names = ['dtype']
159+
160+
def setup(self, dtype):
161+
np.random.seed(1234)
162+
n = 5 * 10**5
163+
sample_size = 100
164+
arr = [i for i in np.random.randint(0, n // 10, size=n)]
165+
if dtype == 'object':
166+
arr = ['s%04d' % i for i in arr]
167+
self.sample = np.random.choice(arr, sample_size)
168+
self.series = pd.Series(arr).astype('category')
169+
170+
def time_isin_categorical(self, dtype):
171+
self.series.isin(self.sample)

doc/source/whatsnew/v0.23.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -954,6 +954,7 @@ Performance Improvements
954954
- Improved performance of :func:`pandas.core.groupby.GroupBy.ffill` and :func:`pandas.core.groupby.GroupBy.bfill` (:issue:`11296`)
955955
- Improved performance of :func:`pandas.core.groupby.GroupBy.any` and :func:`pandas.core.groupby.GroupBy.all` (:issue:`15435`)
956956
- Improved performance of :func:`pandas.core.groupby.GroupBy.pct_change` (:issue:`19165`)
957+
- Improved performance of :func:`Series.isin` in the case of categorical dtypes (:issue:`20003`)
957958
- Fixed a performance regression for :func:`GroupBy.nth` and :func:`GroupBy.last` with some object columns (:issue:`19283`)
958959

959960
.. _whatsnew_0230.docs:

pandas/core/algorithms.py

+7
Original file line numberDiff line numberDiff line change
@@ -407,6 +407,13 @@ def isin(comps, values):
407407
if not isinstance(values, (ABCIndex, ABCSeries, np.ndarray)):
408408
values = construct_1d_object_array_from_listlike(list(values))
409409

410+
if is_categorical_dtype(comps):
411+
# TODO(extension)
412+
# handle categoricals
413+
return comps._values.isin(values)
414+
415+
comps = com._values_from_object(comps)
416+
410417
comps, dtype, _ = _ensure_data(comps)
411418
values, _, _ = _ensure_data(values, dtype=dtype)
412419

pandas/core/arrays/categorical.py

+56
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@
3939
from pandas.util._decorators import (
4040
Appender, cache_readonly, deprecate_kwarg, Substitution)
4141

42+
import pandas.core.algorithms as algorithms
43+
4244
from pandas.io.formats.terminal import get_terminal_size
4345
from pandas.util._validators import validate_bool_kwarg, validate_fillna_kwargs
4446
from pandas.core.config import get_option
@@ -2216,6 +2218,60 @@ def _concat_same_type(self, to_concat):
22162218
def _formatting_values(self):
22172219
return self
22182220

2221+
def isin(self, values):
2222+
"""
2223+
Check whether `values` are contained in Categorical.
2224+
2225+
Return a boolean NumPy Array showing whether each element in
2226+
the Categorical matches an element in the passed sequence of
2227+
`values` exactly.
2228+
2229+
Parameters
2230+
----------
2231+
values : set or list-like
2232+
The sequence of values to test. Passing in a single string will
2233+
raise a ``TypeError``. Instead, turn a single string into a
2234+
list of one element.
2235+
2236+
Returns
2237+
-------
2238+
isin : numpy.ndarray (bool dtype)
2239+
2240+
Raises
2241+
------
2242+
TypeError
2243+
* If `values` is not a set or list-like
2244+
2245+
See Also
2246+
--------
2247+
pandas.Series.isin : equivalent method on Series
2248+
2249+
Examples
2250+
--------
2251+
2252+
>>> s = pd.Categorical(['lama', 'cow', 'lama', 'beetle', 'lama',
2253+
... 'hippo'])
2254+
>>> s.isin(['cow', 'lama'])
2255+
array([ True, True, True, False, True, False])
2256+
2257+
Passing a single string as ``s.isin('lama')`` will raise an error. Use
2258+
a list of one element instead:
2259+
2260+
>>> s.isin(['lama'])
2261+
array([ True, False, True, False, True, False])
2262+
"""
2263+
from pandas.core.series import _sanitize_array
2264+
if not is_list_like(values):
2265+
raise TypeError("only list-like objects are allowed to be passed"
2266+
" to isin(), you passed a [{values_type}]"
2267+
.format(values_type=type(values).__name__))
2268+
values = _sanitize_array(values, None, None)
2269+
null_mask = np.asarray(isna(values))
2270+
code_values = self.categories.get_indexer(values)
2271+
code_values = code_values[null_mask | (code_values >= 0)]
2272+
return algorithms.isin(self.codes, code_values)
2273+
2274+
22192275
# The Series.cat accessor
22202276

22212277

pandas/core/indexes/base.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -3516,7 +3516,7 @@ def isin(self, values, level=None):
35163516
"""
35173517
if level is not None:
35183518
self._validate_index_level(level)
3519-
return algos.isin(np.array(self), values)
3519+
return algos.isin(self, values)
35203520

35213521
def _can_reindex(self, indexer):
35223522
"""

pandas/core/series.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -3567,7 +3567,7 @@ def isin(self, values):
35673567
5 False
35683568
Name: animal, dtype: bool
35693569
"""
3570-
result = algorithms.isin(com._values_from_object(self), values)
3570+
result = algorithms.isin(self, values)
35713571
return self._constructor(result, index=self.index).__finalize__(self)
35723572

35733573
def between(self, left, right, inclusive=True):

pandas/tests/categorical/test_algos.py

+22
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,25 @@ def test_factorized_sort_ordered():
4747

4848
tm.assert_numpy_array_equal(labels, expected_labels)
4949
tm.assert_categorical_equal(uniques, expected_uniques)
50+
51+
52+
def test_isin_cats():
53+
# GH2003
54+
cat = pd.Categorical(["a", "b", np.nan])
55+
56+
result = cat.isin(["a", np.nan])
57+
expected = np.array([True, False, True], dtype=bool)
58+
tm.assert_numpy_array_equal(expected, result)
59+
60+
result = cat.isin(["a", "c"])
61+
expected = np.array([True, False, False], dtype=bool)
62+
tm.assert_numpy_array_equal(expected, result)
63+
64+
65+
@pytest.mark.parametrize("empty", [[], pd.Series(), np.array([])])
66+
def test_isin_empty(empty):
67+
s = pd.Categorical(["a", "b"])
68+
expected = np.array([False, False], dtype=bool)
69+
70+
result = s.isin(empty)
71+
tm.assert_numpy_array_equal(expected, result)

0 commit comments

Comments
 (0)