27
27
maybe_upcast ,
28
28
)
29
29
from pandas .core .dtypes .common import (
30
- is_categorical_dtype ,
31
30
is_datetime64_ns_dtype ,
32
31
is_extension_array_dtype ,
33
32
is_float_dtype ,
37
36
is_object_dtype ,
38
37
is_timedelta64_ns_dtype ,
39
38
)
40
- from pandas .core .dtypes .dtypes import CategoricalDtype , ExtensionDtype , registry
39
+ from pandas .core .dtypes .dtypes import ExtensionDtype , registry
41
40
from pandas .core .dtypes .generic import (
42
41
ABCExtensionArray ,
43
42
ABCIndexClass ,
@@ -529,13 +528,23 @@ def _try_cast(
529
528
if maybe_castable (arr ) and not copy and dtype is None :
530
529
return arr
531
530
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
+
532
538
try :
533
539
# GH#15832: Check if we are requesting a numeric dype and
534
540
# that we can convert the data to the requested dtype.
535
541
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 )
537
547
538
- subarr = maybe_cast_to_datetime (arr , dtype )
539
548
# Take care in creating object arrays (but iterators are not
540
549
# supported):
541
550
if is_object_dtype (dtype ) and (
@@ -549,19 +558,7 @@ def _try_cast(
549
558
# in case of out of bound datetime64 -> always raise
550
559
raise
551
560
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 :
565
562
raise
566
563
else :
567
564
subarr = np .array (arr , dtype = object , copy = copy )
0 commit comments