Skip to content

Commit

Permalink
Backport PR #52516 on branch 2.0.x (REGR: fix Series construction fro…
Browse files Browse the repository at this point in the history
…m dict for subclasses) (#52520)

Backport PR #52516: REGR: fix Series construction from dict for subclasses

Co-authored-by: Joris Van den Bossche <jorisvandenbossche@gmail.com>
  • Loading branch information
meeseeksmachine and jorisvandenbossche committed Apr 7, 2023
1 parent 49c020a commit 797ff80
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 7 deletions.
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v2.0.1.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ including other versions of pandas.

Fixed regressions
~~~~~~~~~~~~~~~~~
-
- Fixed regression for subclassed Series when constructing from a dictionary (:issue:`52445`)

.. ---------------------------------------------------------------------------
.. _whatsnew_201.bug_fixes:
Expand Down
7 changes: 1 addition & 6 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -562,12 +562,7 @@ def _init_dict(
keys, values = (), []

# Input is now list-like, so rely on "standard" construction:

s = self._constructor(
values,
index=keys,
dtype=dtype,
)
s = Series(values, index=keys, dtype=dtype)

# Now we just make sure the order is respected, if any
if data and index is not None:
Expand Down
18 changes: 18 additions & 0 deletions pandas/tests/series/test_subclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,21 @@ def test_equals(self):
s2 = tm.SubclassedSeries([1, 2, 3])
assert s1.equals(s2)
assert s2.equals(s1)


class SubclassedSeries(pd.Series):
@property
def _constructor(self):
def _new(*args, **kwargs):
# some constructor logic that accesses the Series' name
if self.name == "test":
return pd.Series(*args, **kwargs)
return SubclassedSeries(*args, **kwargs)

return _new


def test_constructor_from_dict():
# https://github.com/pandas-dev/pandas/issues/52445
result = SubclassedSeries({"a": 1, "b": 2, "c": 3})
assert isinstance(result, SubclassedSeries)

0 comments on commit 797ff80

Please sign in to comment.