Skip to content

Backport PR #55537 on branch 2.1.x (BUG: Series inferring new string dtype even if dtype is given for scalar value) #55635

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion pandas/core/construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -540,6 +540,7 @@ def sanitize_array(
-------
np.ndarray or ExtensionArray
"""
original_dtype = dtype
if isinstance(data, ma.MaskedArray):
data = sanitize_masked_array(data)

Expand All @@ -562,7 +563,11 @@ def sanitize_array(
if not is_list_like(data):
if index is None:
raise ValueError("index must be specified when data is not list-like")
if isinstance(data, str) and using_pyarrow_string_dtype():
if (
isinstance(data, str)
and using_pyarrow_string_dtype()
and original_dtype is None
):
from pandas.core.arrays.string_ import StringDtype

dtype = StringDtype("pyarrow_numpy")
Expand Down
8 changes: 8 additions & 0 deletions pandas/tests/series/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -2123,6 +2123,14 @@ def test_series_string_inference_storage_definition(self):
result = Series(["a", "b"], dtype="string")
tm.assert_series_equal(result, expected)

def test_series_constructor_infer_string_scalar(self):
# GH#55537
with pd.option_context("future.infer_string", True):
ser = Series("a", index=[1, 2], dtype="string[python]")
expected = Series(["a", "a"], index=[1, 2], dtype="string[python]")
tm.assert_series_equal(ser, expected)
assert ser.dtype.storage == "python"


class TestSeriesConstructorIndexCoercion:
def test_series_constructor_datetimelike_index_coercion(self):
Expand Down