@@ -1654,12 +1654,28 @@ def cast_scalar_to_array(
1654
1654
1655
1655
"""
1656
1656
if dtype is None :
1657
- dtype , fill_value = infer_dtype_from_scalar (value )
1657
+ dtype , value = infer_dtype_from_scalar (value )
1658
1658
else :
1659
- fill_value = value
1659
+ if shape and is_integer_dtype (dtype ) and isna (value ):
1660
+ # coerce if we have nan for an integer dtype
1661
+ dtype = np .dtype ("float64" )
1662
+ elif isinstance (dtype , np .dtype ) and dtype .kind in ("U" , "S" ):
1663
+ # we need to coerce to object dtype to avoid
1664
+ # to allow numpy to take our string as a scalar value
1665
+ dtype = np .dtype ("object" )
1666
+ if not isna (value ):
1667
+ value = ensure_str (value )
1668
+ elif dtype .kind in ["M" , "m" ]:
1669
+ # GH38032: filling in Timedelta/Timestamp drops nanoseconds
1670
+ if isinstance (value , (Timedelta , Timestamp )):
1671
+ value = value .to_numpy ()
1672
+ # GH36541: filling datetime-like array directly with pd.NaT
1673
+ # raises ValueError: cannot convert float NaN to integer
1674
+ elif is_valid_nat_for_dtype (value , dtype ):
1675
+ value = np .datetime64 ("NaT" )
1660
1676
1661
1677
values = np .empty (shape , dtype = dtype )
1662
- values .fill (fill_value )
1678
+ values .fill (value )
1663
1679
1664
1680
return values
1665
1681
@@ -1687,27 +1703,7 @@ def construct_1d_arraylike_from_scalar(
1687
1703
subarr = cls ._from_sequence ([value ] * length , dtype = dtype )
1688
1704
1689
1705
else :
1690
-
1691
- if length and is_integer_dtype (dtype ) and isna (value ):
1692
- # coerce if we have nan for an integer dtype
1693
- dtype = np .dtype ("float64" )
1694
- elif isinstance (dtype , np .dtype ) and dtype .kind in ("U" , "S" ):
1695
- # we need to coerce to object dtype to avoid
1696
- # to allow numpy to take our string as a scalar value
1697
- dtype = np .dtype ("object" )
1698
- if not isna (value ):
1699
- value = ensure_str (value )
1700
- elif dtype .kind in ["M" , "m" ]:
1701
- # GH38032: filling in Timedelta/Timestamp drops nanoseconds
1702
- if isinstance (value , (Timedelta , Timestamp )):
1703
- value = value .to_numpy ()
1704
- # GH36541: filling datetime-like array directly with pd.NaT
1705
- # raises ValueError: cannot convert float NaN to integer
1706
- elif is_valid_nat_for_dtype (value , dtype ):
1707
- value = np .datetime64 ("NaT" )
1708
-
1709
- subarr = np .empty (length , dtype = dtype )
1710
- subarr .fill (value )
1706
+ subarr = cast_scalar_to_array (length , value , dtype )
1711
1707
1712
1708
return subarr
1713
1709
0 commit comments