2727 maybe_upcast ,
2828)
2929from pandas .core .dtypes .common import (
30- is_categorical_dtype ,
3130 is_datetime64_ns_dtype ,
3231 is_extension_array_dtype ,
3332 is_float_dtype ,
3736 is_object_dtype ,
3837 is_timedelta64_ns_dtype ,
3938)
40- from pandas .core .dtypes .dtypes import CategoricalDtype , ExtensionDtype , registry
39+ from pandas .core .dtypes .dtypes import ExtensionDtype , registry
4140from pandas .core .dtypes .generic import (
4241 ABCExtensionArray ,
4342 ABCIndexClass ,
@@ -529,13 +528,23 @@ def _try_cast(
529528 if maybe_castable (arr ) and not copy and dtype is None :
530529 return arr
531530
531+ if isinstance (dtype , ExtensionDtype ) and dtype .kind != "M" :
532+ # create an extension array from its dtype
533+ # DatetimeTZ case needs to go through maybe_cast_to_datetime
534+ array_type = dtype .construct_array_type ()._from_sequence
535+ subarr = array_type (arr , dtype = dtype , copy = copy )
536+ return subarr
537+
532538 try :
533539 # GH#15832: Check if we are requesting a numeric dype and
534540 # that we can convert the data to the requested dtype.
535541 if is_integer_dtype (dtype ):
536- subarr = maybe_cast_to_integer_array (arr , dtype )
542+ # this will raise if we have e.g. floats
543+ maybe_cast_to_integer_array (arr , dtype )
544+ subarr = arr
545+ else :
546+ subarr = maybe_cast_to_datetime (arr , dtype )
537547
538- subarr = maybe_cast_to_datetime (arr , dtype )
539548 # Take care in creating object arrays (but iterators are not
540549 # supported):
541550 if is_object_dtype (dtype ) and (
@@ -549,19 +558,7 @@ def _try_cast(
549558 # in case of out of bound datetime64 -> always raise
550559 raise
551560 except (ValueError , TypeError ):
552- if is_categorical_dtype (dtype ):
553- # We *do* allow casting to categorical, since we know
554- # that Categorical is the only array type for 'category'.
555- dtype = cast (CategoricalDtype , dtype )
556- subarr = dtype .construct_array_type ()(
557- arr , dtype .categories , ordered = dtype .ordered
558- )
559- elif is_extension_array_dtype (dtype ):
560- # create an extension array from its dtype
561- dtype = cast (ExtensionDtype , dtype )
562- array_type = dtype .construct_array_type ()._from_sequence
563- subarr = array_type (arr , dtype = dtype , copy = copy )
564- elif dtype is not None and raise_cast_failure :
561+ if dtype is not None and raise_cast_failure :
565562 raise
566563 else :
567564 subarr = np .array (arr , dtype = object , copy = copy )
0 commit comments