Skip to content

Commit 4468823

Browse files
authored
ENH: Make Series.update() use objects coercible to Series (#33502)
1 parent 619ce1b commit 4468823

File tree

3 files changed

+44
-1
lines changed

3 files changed

+44
-1
lines changed

doc/source/whatsnew/v1.1.0.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,8 @@ Other enhancements
9898
This can be used to set a custom compression level, e.g.,
9999
``df.to_csv(path, compression={'method': 'gzip', 'compresslevel': 1}``
100100
(:issue:`33196`)
101+
- :meth:`Series.update` now accepts objects that can be coerced to a :class:`Series`,
102+
such as ``dict`` and ``list``, mirroring the behavior of :meth:`DataFrame.update` (:issue:`33215`)
101103
- :meth:`~pandas.core.groupby.GroupBy.transform` and :meth:`~pandas.core.groupby.GroupBy.aggregate` has gained ``engine`` and ``engine_kwargs`` arguments that supports executing functions with ``Numba`` (:issue:`32854`, :issue:`33388`)
102104
- :meth:`~pandas.core.resample.Resampler.interpolate` now supports SciPy interpolation method :class:`scipy.interpolate.CubicSpline` as method ``cubicspline`` (:issue:`33670`)
103105
-

pandas/core/series.py

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2786,7 +2786,7 @@ def update(self, other) -> None:
27862786
27872787
Parameters
27882788
----------
2789-
other : Series
2789+
other : Series, or object coercible into Series
27902790
27912791
Examples
27922792
--------
@@ -2824,7 +2824,30 @@ def update(self, other) -> None:
28242824
1 2
28252825
2 6
28262826
dtype: int64
2827+
2828+
``other`` can also be a non-Series object type
2829+
that is coercible into a Series
2830+
2831+
>>> s = pd.Series([1, 2, 3])
2832+
>>> s.update([4, np.nan, 6])
2833+
>>> s
2834+
0 4
2835+
1 2
2836+
2 6
2837+
dtype: int64
2838+
2839+
>>> s = pd.Series([1, 2, 3])
2840+
>>> s.update({1: 9})
2841+
>>> s
2842+
0 1
2843+
1 9
2844+
2 3
2845+
dtype: int64
28272846
"""
2847+
2848+
if not isinstance(other, Series):
2849+
other = Series(other)
2850+
28282851
other = other.reindex_like(self)
28292852
mask = notna(other)
28302853

pandas/tests/series/methods/test_update.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,21 @@ def test_update_dtypes(self, other, dtype, expected):
5656
ser.update(other)
5757

5858
tm.assert_series_equal(ser, expected)
59+
60+
@pytest.mark.parametrize(
61+
"series, other, expected",
62+
[
63+
# update by key
64+
(
65+
Series({"a": 1, "b": 2, "c": 3, "d": 4}),
66+
{"b": 5, "c": np.nan},
67+
Series({"a": 1, "b": 5, "c": 3, "d": 4}),
68+
),
69+
# update by position
70+
(Series([1, 2, 3, 4]), [np.nan, 5, 1], Series([1, 5, 1, 4])),
71+
],
72+
)
73+
def test_update_from_non_series(self, series, other, expected):
74+
# GH 33215
75+
series.update(other)
76+
tm.assert_series_equal(series, expected)

0 commit comments

Comments
 (0)