Skip to content

Commit 8a77f9e

Browse files
committed
implement __contains__ for Categorical
1 parent a5c02d5 commit 8a77f9e

File tree

3 files changed

+19
-0
lines changed

3 files changed

+19
-0
lines changed

asv_bench/benchmarks/categoricals.py

+13
Original file line numberDiff line numberDiff line change
@@ -169,3 +169,16 @@ def setup(self, dtype):
169169

170170
def time_isin_categorical(self, dtype):
171171
self.series.isin(self.sample)
172+
173+
174+
class Slicing(object):
175+
176+
def setup(self):
177+
n = 1 * 10**4
178+
self.df = pd.DataFrame(
179+
dict(A=range(n * 3)),
180+
index=pd.CategoricalIndex(list('a' * n + 'b' * n + 'c' * n))
181+
)
182+
183+
def time_loc_categorical(self):
184+
self.df.loc['b']

doc/source/whatsnew/v0.23.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -1080,6 +1080,7 @@ Performance Improvements
10801080
- Improved performance of :func:`Series.isin` in the case of categorical dtypes (:issue:`20003`)
10811081
- Improved performance of ``getattr(Series, attr)`` when the Series has certain index types. This manifiested in slow printing of large Series with a ``DatetimeIndex`` (:issue:`19764`)
10821082
- Fixed a performance regression for :func:`GroupBy.nth` and :func:`GroupBy.last` with some object columns (:issue:`19283`)
1083+
- Improved performance of :meth:`Categorical.loc` (:issue:`20395`)
10831084

10841085
.. _whatsnew_0230.docs:
10851086

pandas/core/arrays/categorical.py

+5
Original file line numberDiff line numberDiff line change
@@ -1846,6 +1846,11 @@ def __iter__(self):
18461846
"""Returns an Iterator over the values of this Categorical."""
18471847
return iter(self.get_values().tolist())
18481848

1849+
def __contains__(self, key):
1850+
"""Returns True if `key` is in this Categorical."""
1851+
code_values = self.categories.get_indexer([key])
1852+
return code_values[0] in self.codes
1853+
18491854
def _tidy_repr(self, max_vals=10, footer=True):
18501855
""" a short repr displaying only max_vals and an optional (but default
18511856
footer)

0 commit comments

Comments
 (0)