|
6 | 6 |
|
7 | 7 | from pandas._libs import lib, tslib, tslibs |
8 | 8 | from pandas._libs.tslibs import OutOfBoundsDatetime, Period, iNaT |
9 | | -from pandas.compat import PY3, string_types, text_type |
| 9 | +from pandas.compat import PY3, string_types, text_type, to_str |
10 | 10 |
|
11 | 11 | from .common import ( |
12 | 12 | _INT64_DTYPE, _NS_DTYPE, _POSSIBLY_CAST_DTYPES, _TD_DTYPE, _string_dtypes, |
@@ -1216,11 +1216,16 @@ def construct_1d_arraylike_from_scalar(value, length, dtype): |
1216 | 1216 | if not isinstance(dtype, (np.dtype, type(np.dtype))): |
1217 | 1217 | dtype = dtype.dtype |
1218 | 1218 |
|
1219 | | - # coerce if we have nan for an integer dtype |
1220 | | - # GH 22858: only cast to float if an index |
1221 | | - # (passed here as length) is specified |
1222 | 1219 | if length and is_integer_dtype(dtype) and isna(value): |
1223 | | - dtype = np.float64 |
| 1220 | + # coerce if we have nan for an integer dtype |
| 1221 | + dtype = np.dtype('float64') |
| 1222 | + elif isinstance(dtype, np.dtype) and dtype.kind in ("U", "S"): |
| 1223 | + # we need to coerce to object dtype to avoid |
| 1224 | + # to allow numpy to take our string as a scalar value |
| 1225 | + dtype = object |
| 1226 | + if not isna(value): |
| 1227 | + value = to_str(value) |
| 1228 | + |
1224 | 1229 | subarr = np.empty(length, dtype=dtype) |
1225 | 1230 | subarr.fill(value) |
1226 | 1231 |
|
|
0 commit comments