19
19
is_list_like , _values_from_object ,
20
20
_possibly_cast_to_datetime , _possibly_castable ,
21
21
_possibly_convert_platform , _try_sort ,
22
- ABCSparseArray , _maybe_match_name ,
22
+ ABCSparseArray , _maybe_match_name , _coerce_to_dtype ,
23
23
_ensure_object , SettingWithCopyError )
24
24
from pandas .core .index import (Index , MultiIndex , InvalidIndexError ,
25
25
_ensure_index )
@@ -2434,7 +2434,7 @@ def _sanitize_array(data, index, dtype=None, copy=False,
2434
2434
""" sanitize input data to an ndarray, copy if specified, coerce to the dtype if specified """
2435
2435
2436
2436
if dtype is not None :
2437
- dtype = np . dtype (dtype )
2437
+ dtype = _coerce_to_dtype (dtype )
2438
2438
2439
2439
if isinstance (data , ma .MaskedArray ):
2440
2440
mask = ma .getmaskarray (data )
@@ -2455,9 +2455,11 @@ def _try_cast(arr, take_fast_path):
2455
2455
arr = _possibly_cast_to_datetime (arr , dtype )
2456
2456
subarr = pa .array (arr , dtype = dtype , copy = copy )
2457
2457
except (ValueError , TypeError ):
2458
- if dtype is not None and raise_cast_failure :
2458
+ if com .is_categorical_dtype (dtype ):
2459
+ subarr = Categorical (arr )
2460
+ elif dtype is not None and raise_cast_failure :
2459
2461
raise
2460
- else : # pragma: no cover
2462
+ else :
2461
2463
subarr = pa .array (arr , dtype = object , copy = copy )
2462
2464
return subarr
2463
2465
0 commit comments