@@ -1192,6 +1192,26 @@ def map(self, mapper):
1192
1192
__le__ = _cat_compare_op (operator .le )
1193
1193
__ge__ = _cat_compare_op (operator .ge )
1194
1194
1195
+ def _validate_insert_value (self , value ) -> int :
1196
+ code = self .categories .get_indexer ([value ])
1197
+ if (code == - 1 ) and not (is_scalar (value ) and isna (value )):
1198
+ raise TypeError (
1199
+ "cannot insert an item into a CategoricalIndex "
1200
+ "that is not already an existing category"
1201
+ )
1202
+ return code [0 ]
1203
+
1204
+ def _validate_searchsorted_value (self , value ):
1205
+ # searchsorted is very performance sensitive. By converting codes
1206
+ # to same dtype as self.codes, we get much faster performance.
1207
+ if is_scalar (value ):
1208
+ codes = self .categories .get_loc (value )
1209
+ codes = self .codes .dtype .type (codes )
1210
+ else :
1211
+ locs = [self .categories .get_loc (x ) for x in value ]
1212
+ codes = np .array (locs , dtype = self .codes .dtype )
1213
+ return codes
1214
+
1195
1215
def _validate_fill_value (self , fill_value ):
1196
1216
"""
1197
1217
Convert a user-facing fill_value to a representation to use with our
@@ -1299,15 +1319,8 @@ def memory_usage(self, deep=False):
1299
1319
1300
1320
@doc (_shared_docs ["searchsorted" ], klass = "Categorical" )
1301
1321
def searchsorted (self , value , side = "left" , sorter = None ):
1302
- # searchsorted is very performance sensitive. By converting codes
1303
- # to same dtype as self.codes, we get much faster performance.
1304
- if is_scalar (value ):
1305
- codes = self .categories .get_loc (value )
1306
- codes = self .codes .dtype .type (codes )
1307
- else :
1308
- locs = [self .categories .get_loc (x ) for x in value ]
1309
- codes = np .array (locs , dtype = self .codes .dtype )
1310
- return self .codes .searchsorted (codes , side = side , sorter = sorter )
1322
+ value = self ._validate_searchsorted_value (value )
1323
+ return self .codes .searchsorted (value , side = side , sorter = sorter )
1311
1324
1312
1325
def isna (self ):
1313
1326
"""
0 commit comments