@@ -464,16 +464,11 @@ def maybe_cast_pointwise_result(
464
464
"""
465
465
466
466
if isinstance (dtype , ExtensionDtype ):
467
- if not isinstance (dtype , (CategoricalDtype , DatetimeTZDtype )):
468
- # TODO: avoid this special-casing
469
- # We have to special case categorical so as not to upcast
470
- # things like counts back to categorical
471
-
472
- cls = dtype .construct_array_type ()
473
- if same_dtype :
474
- result = _maybe_cast_to_extension_array (cls , result , dtype = dtype )
475
- else :
476
- result = _maybe_cast_to_extension_array (cls , result )
467
+ cls = dtype .construct_array_type ()
468
+ if same_dtype :
469
+ result = _maybe_cast_to_extension_array (cls , result , dtype = dtype )
470
+ else :
471
+ result = _maybe_cast_to_extension_array (cls , result )
477
472
478
473
elif (numeric_only and dtype .kind in "iufcb" ) or not numeric_only :
479
474
result = maybe_downcast_to_dtype (result , dtype )
@@ -498,11 +493,14 @@ def _maybe_cast_to_extension_array(
498
493
-------
499
494
ExtensionArray or obj
500
495
"""
501
- from pandas . core . arrays . string_ import BaseStringArray
496
+ result : ArrayLike
502
497
503
- # Everything can be converted to StringArrays, but we may not want to convert
504
- if issubclass (cls , BaseStringArray ) and lib .infer_dtype (obj ) != "string" :
505
- return obj
498
+ if dtype is not None :
499
+ try :
500
+ result = cls ._from_scalars (obj , dtype = dtype )
501
+ except (TypeError , ValueError ):
502
+ return obj
503
+ return result
506
504
507
505
try :
508
506
result = cls ._from_sequence (obj , dtype = dtype )
0 commit comments