File tree 3 files changed +13
-15
lines changed
3 files changed +13
-15
lines changed Original file line number Diff line number Diff line change @@ -1177,13 +1177,7 @@ def _validate_where_value(self, value):
1177
1177
return self ._validate_listlike (value )
1178
1178
1179
1179
def _validate_insert_value (self , value ) -> int :
1180
- code = self .categories .get_indexer ([value ])
1181
- if (code == - 1 ) and not (is_scalar (value ) and isna (value )):
1182
- raise TypeError (
1183
- "cannot insert an item into a CategoricalIndex "
1184
- "that is not already an existing category"
1185
- )
1186
- return code [0 ]
1180
+ return self ._validate_fill_value (value )
1187
1181
1188
1182
def _validate_searchsorted_value (self , value ):
1189
1183
# searchsorted is very performance sensitive. By converting codes
@@ -1213,7 +1207,7 @@ def _validate_fill_value(self, fill_value):
1213
1207
ValueError
1214
1208
"""
1215
1209
1216
- if isna (fill_value ):
1210
+ if is_valid_nat_for_dtype (fill_value , self . categories . dtype ):
1217
1211
fill_value = - 1
1218
1212
elif fill_value in self .categories :
1219
1213
fill_value = self ._unbox_scalar (fill_value )
Original file line number Diff line number Diff line change @@ -171,11 +171,8 @@ def test_insert(self):
171
171
tm .assert_index_equal (result , expected , exact = True )
172
172
173
173
# invalid
174
- msg = (
175
- "cannot insert an item into a CategoricalIndex that is not "
176
- "already an existing category"
177
- )
178
- with pytest .raises (TypeError , match = msg ):
174
+ msg = "'fill_value=d' is not present in this Categorical's categories"
175
+ with pytest .raises (ValueError , match = msg ):
179
176
ci .insert (0 , "d" )
180
177
181
178
# GH 18295 (test missing)
@@ -184,6 +181,12 @@ def test_insert(self):
184
181
result = CategoricalIndex (list ("aabcb" )).insert (1 , na )
185
182
tm .assert_index_equal (result , expected )
186
183
184
+ def test_insert_na_mismatched_dtype (self ):
185
+ ci = pd .CategoricalIndex ([0 , 1 , 1 ])
186
+ msg = "'fill_value=NaT' is not present in this Categorical's categories"
187
+ with pytest .raises (ValueError , match = msg ):
188
+ ci .insert (0 , pd .NaT )
189
+
187
190
def test_delete (self ):
188
191
189
192
ci = self .create_index ()
Original file line number Diff line number Diff line change @@ -76,9 +76,10 @@ def test_loc_scalar(self):
76
76
"cannot insert an item into a CategoricalIndex that is not "
77
77
"already an existing category"
78
78
)
79
- with pytest .raises (TypeError , match = msg ):
79
+ msg = "'fill_value=d' is not present in this Categorical's categories"
80
+ with pytest .raises (ValueError , match = msg ):
80
81
df .loc ["d" , "A" ] = 10
81
- with pytest .raises (TypeError , match = msg ):
82
+ with pytest .raises (ValueError , match = msg ):
82
83
df .loc ["d" , "C" ] = 10
83
84
84
85
with pytest .raises (KeyError , match = "^1$" ):
You can’t perform that action at this time.
0 commit comments