nebius/SWE-rebench-V2-PRs huggingface dataset:
Repository: pandas-dev/pandas
Pull request #55629 (2023-10-22 15:20:41)

Backport PR #55620 on branch 2.1.x (BUG: Groupby not keeping object dtype when infer string is set)
Backport PR #55620: BUG: Groupby not keeping object dtype when infer string is set


Patch:
diff --git a/doc/source/whatsnew/v2.1.2.rst b/doc/source/whatsnew/v2.1.2.rst
index 97a718dd49..175c534ce0 100644
--- a/doc/source/whatsnew/v2.1.2.rst
+++ b/doc/source/whatsnew/v2.1.2.rst
@@ -23,6 +23,7 @@ Fixed regressions
 
 Bug fixes
 ~~~~~~~~~
+- Fixed bug in :class:`.DataFrameGroupBy` reductions not preserving object dtype when ``infer_string`` is set (:issue:`55620`)
 - Fixed bug in :meth:`Categorical.equals` if other has arrow backed string dtype (:issue:`55364`)
 - Fixed bug in :meth:`DataFrame.__setitem__` not inferring string dtype for zero-dimensional array with ``infer_string=True`` (:issue:`55366`)
 - Fixed bug in :meth:`DataFrame.idxmin` and :meth:`DataFrame.idxmax` raising for arrow dtypes (:issue:`55368`)
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 7fa69a7043..d9fdf72eed 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -1855,8 +1855,7 @@ class GroupBy(BaseGroupBy[NDFrameT]):
             ser = Series(values, copy=False)
         else:
             # We only get here with values.dtype == object
-            # TODO: special case not needed with ArrayManager
-            df = DataFrame(values.T)
+            df = DataFrame(values.T, dtype=values.dtype)
             # bc we split object blocks in grouped_reduce, we have only 1 col
             # otherwise we'd have to worry about block-splitting GH#39329
             assert df.shape[1] == 1


Test patch:
diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py
index 78a0497ef6..7726dbe699 100644
--- a/pandas/tests/groupby/test_groupby.py
+++ b/pandas/tests/groupby/test_groupby.py
@@ -5,6 +5,7 @@ import re
 import numpy as np
 import pytest
 
+from pandas.compat import pa_version_under7p0
 from pandas.errors import (
     PerformanceWarning,
     SpecificationError,
@@ -2513,13 +2514,24 @@ def test_groupby_column_index_name_lost(func):
     tm.assert_index_equal(result, expected)
 
 
-def test_groupby_duplicate_columns():
+@pytest.mark.parametrize(
+    "infer_string",
+    [
+        False,
+        pytest.param(
+            True,
+            marks=pytest.mark.skipif(pa_version_under7p0, reason="arrow not installed"),
+        ),
+    ],
+)
+def test_groupby_duplicate_columns(infer_string):
     # GH: 31735
     df = DataFrame(
         {"A": ["f", "e", "g", "h"], "B": ["a", "b", "c", "d"], "C": [1, 2, 3, 4]}
     ).astype(object)
     df.columns = ["A", "B", "B"]
-    result = df.groupby([0, 0, 0, 0]).min()
+    with pd.option_context("future.infer_string", infer_string):
+        result = df.groupby([0, 0, 0, 0]).min()
     expected = DataFrame(
         [["e", "a", 1]], index=np.array([0]), columns=["A", "B", "B"], dtype=object
     )
Repository: pandas-dev/pandas
Pull request #55635 (2023-10-22 19:49:11)

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


Patch:
diff --git a/pandas/core/construction.py b/pandas/core/construction.py
index e661d590ab..5903187769 100644
--- a/pandas/core/construction.py
+++ b/pandas/core/construction.py
@@ -540,6 +540,7 @@ def sanitize_array(
     -------
     np.ndarray or ExtensionArray
     """
+    original_dtype = dtype
     if isinstance(data, ma.MaskedArray):
         data = sanitize_masked_array(data)
 
@@ -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")


Test patch:
diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py
index 2c3fdf6277..8cc891e1ee 100644
--- a/pandas/tests/series/test_constructors.py
+++ b/pandas/tests/series/test_constructors.py
@@ -2123,6 +2123,14 @@ class TestSeriesConstructors:
             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):