From 947847f9206bb99b63b8965291443d29431d9857 Mon Sep 17 00:00:00 2001 From: tp Date: Thu, 9 Apr 2020 13:45:26 +0100 Subject: [PATCH] API: More permissive conversion to StringDtype --- pandas/core/arrays/string_.py | 11 ++++++----- pandas/core/internals/blocks.py | 6 +++++- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py index dbca8e74f5e1b..c452f3fbc87ae 100644 --- a/pandas/core/arrays/string_.py +++ b/pandas/core/arrays/string_.py @@ -203,11 +203,12 @@ def _from_sequence(cls, scalars, dtype=None, copy=False): # TODO: it would be nice to do this in _validate / lib.is_string_array # We are already doing a scan over the values there. na_values = isna(result) - if na_values.any(): - if result is scalars: - # force a copy now, if we haven't already - result = result.copy() - result[na_values] = StringDtype.na_value + if na_values.any() and result is scalars: + # force a copy now, if we haven't already + result = result.copy() + result = np.asarray(result, str) + result = np.asarray(result, object) + result[na_values] = StringDtype.na_value return cls(result) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index d12b78f8d046f..a46aab856d569 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -565,7 +565,11 @@ def astype(self, dtype, copy: bool = False, errors: str = "raise"): # force the copy here if self.is_extension: # TODO: Should we try/except this astype? - values = self.values.astype(dtype) + if is_extension_array_dtype(dtype): + arr_type = dtype.construct_array_type() + values = arr_type._from_sequence(self.values, dtype=dtype) + else: + values = self.values.astype(dtype) else: if issubclass(dtype.type, str):