Skip to content

Commit b761844

Browse files
Backport PR #54699 on branch 2.1.x (BUG: setitem with object type inserting Series maintains Series) (#54760)
Backport PR #54699: BUG: setitem with object type inserting Series maintains Series Co-authored-by: Matthew Roeschke <[email protected]>
1 parent 4f66163 commit b761844

File tree

3 files changed

+20
-1
lines changed

3 files changed

+20
-1
lines changed

doc/source/whatsnew/v2.1.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -729,6 +729,7 @@ Indexing
729729
- Bug in :meth:`DataFrame.__setitem__` losing dtype when setting a :class:`DataFrame` into duplicated columns (:issue:`53143`)
730730
- Bug in :meth:`DataFrame.__setitem__` with a boolean mask and :meth:`DataFrame.putmask` with mixed non-numeric dtypes and a value other than ``NaN`` incorrectly raising ``TypeError`` (:issue:`53291`)
731731
- Bug in :meth:`DataFrame.iloc` when using ``nan`` as the only element (:issue:`52234`)
732+
- Bug in :meth:`Series.loc` casting :class:`Series` to ``np.dnarray`` when assigning :class:`Series` at predefined index of ``object`` dtype :class:`Series` (:issue:`48933`)
732733

733734
Missing
734735
^^^^^^^

pandas/core/internals/blocks.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -1133,7 +1133,9 @@ def setitem(self, indexer, value, using_cow: bool = False) -> Block:
11331133
# length checking
11341134
check_setitem_lengths(indexer, value, values)
11351135

1136-
value = extract_array(value, extract_numpy=True)
1136+
if self.dtype != _dtype_obj:
1137+
# GH48933: extract_array would convert a pd.Series value to np.ndarray
1138+
value = extract_array(value, extract_numpy=True)
11371139
try:
11381140
casted = np_can_hold_element(values.dtype, value)
11391141
except LossySetitemError:

pandas/tests/indexing/test_indexing.py

+16
Original file line numberDiff line numberDiff line change
@@ -1132,3 +1132,19 @@ def test_scalar_setitem_series_with_nested_value_length1(value, indexer_sli):
11321132
assert (ser.loc[0] == value).all()
11331133
else:
11341134
assert ser.loc[0] == value
1135+
1136+
1137+
def test_object_dtype_series_set_series_element():
1138+
# GH 48933
1139+
s1 = Series(dtype="O", index=["a", "b"])
1140+
1141+
s1["a"] = Series()
1142+
s1.loc["b"] = Series()
1143+
1144+
tm.assert_series_equal(s1.loc["a"], Series())
1145+
tm.assert_series_equal(s1.loc["b"], Series())
1146+
1147+
s2 = Series(dtype="O", index=["a", "b"])
1148+
1149+
s2.iloc[1] = Series()
1150+
tm.assert_series_equal(s2.iloc[1], Series())

0 commit comments

Comments
 (0)