From b9d41e46024e0152ad461e221722d0991754f65a Mon Sep 17 00:00:00 2001 From: Patrick Hoefler <61934744+phofl@users.noreply.github.com> Date: Fri, 17 Jan 2025 20:11:37 +0100 Subject: [PATCH] REGR: from_records not initializing subclasses properly (#60726) * REGR: from_records not initializing subclasses properly * Move whatsnew --- doc/source/whatsnew/v2.3.3.rst | 6 ++++++ pandas/core/frame.py | 6 ++++-- pandas/tests/frame/test_subclass.py | 7 +++++++ 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/doc/source/whatsnew/v2.3.3.rst b/doc/source/whatsnew/v2.3.3.rst index eeba61a686c73..2f95c62c8f268 100644 --- a/doc/source/whatsnew/v2.3.3.rst +++ b/doc/source/whatsnew/v2.3.3.rst @@ -58,6 +58,12 @@ Bug fixes - The :meth:`DataFrame.iloc` now works correctly with ``copy_on_write`` option when assigning values after subsetting the columns of a homogeneous DataFrame (:issue:`60309`) +Other Bug fixes +~~~~~~~~~~~~~~~~ + +- Fixed regression in :meth:`DataFrame.from_records` not initializing subclasses properly (:issue:`57008`) + + .. --------------------------------------------------------------------------- .. _whatsnew_233.contributors: diff --git a/pandas/core/frame.py b/pandas/core/frame.py index c99ba07a55d46..cc260770cbd78 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2549,8 +2549,10 @@ def maybe_reorder( manager = _get_option("mode.data_manager", silent=True) mgr = arrays_to_mgr(arrays, columns, result_index, typ=manager) - - return cls._from_mgr(mgr, axes=mgr.axes) + df = DataFrame._from_mgr(mgr, axes=mgr.axes) + if cls is not DataFrame: + return cls(df, copy=False) + return df def to_records( self, index: bool = True, column_dtypes=None, index_dtypes=None diff --git a/pandas/tests/frame/test_subclass.py b/pandas/tests/frame/test_subclass.py index 855b58229cbdb..39a29406c6e9a 100644 --- a/pandas/tests/frame/test_subclass.py +++ b/pandas/tests/frame/test_subclass.py @@ -784,6 +784,13 @@ def test_constructor_with_metadata(): assert isinstance(subset, MySubclassWithMetadata) +def test_constructor_with_metadata_from_records(): + # GH#57008 + df = MySubclassWithMetadata.from_records([{"a": 1, "b": 2}]) + assert df.my_metadata is None + assert type(df) is MySubclassWithMetadata + + class SimpleDataFrameSubClass(DataFrame): """A subclass of DataFrame that does not define a constructor."""