Skip to content

Commit f19f81f

Browse files
authored
BUG: incompatible dtype when creating string column with loc (#55249)
dont raise unnecessary warning
1 parent cae3f16 commit f19f81f

File tree

4 files changed

+20
-5
lines changed

4 files changed

+20
-5
lines changed

doc/source/whatsnew/v2.1.2.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ including other versions of pandas.
1313

1414
Fixed regressions
1515
~~~~~~~~~~~~~~~~~
16-
-
16+
- Fixed bug where PDEP-6 warning about setting an item of an incompatible dtype was being shown when creating a new conditional column (:issue:`55025`)
1717
-
1818

1919
.. ---------------------------------------------------------------------------

pandas/core/dtypes/missing.py

+3
Original file line numberDiff line numberDiff line change
@@ -624,6 +624,9 @@ def infer_fill_value(val):
624624
return np.array("NaT", dtype=DT64NS_DTYPE)
625625
elif dtype in ["timedelta", "timedelta64"]:
626626
return np.array("NaT", dtype=TD64NS_DTYPE)
627+
return np.array(np.nan, dtype=object)
628+
elif val.dtype.kind == "U":
629+
return np.array(np.nan, dtype=val.dtype)
627630
return np.nan
628631

629632

pandas/tests/frame/indexing/test_indexing.py

+15
Original file line numberDiff line numberDiff line change
@@ -1890,6 +1890,21 @@ def test_setitem_dict_and_set_disallowed_multiindex(self, key):
18901890
df.loc[key] = 1
18911891

18921892

1893+
def test_adding_new_conditional_column() -> None:
1894+
# https://github.com/pandas-dev/pandas/issues/55025
1895+
df = DataFrame({"x": [1]})
1896+
df.loc[df["x"] == 1, "y"] = "1"
1897+
expected = DataFrame({"x": [1], "y": ["1"]})
1898+
tm.assert_frame_equal(df, expected)
1899+
1900+
df = DataFrame({"x": [1]})
1901+
# try inserting something which numpy would store as 'object'
1902+
value = lambda x: x
1903+
df.loc[df["x"] == 1, "y"] = value
1904+
expected = DataFrame({"x": [1], "y": [value]})
1905+
tm.assert_frame_equal(df, expected)
1906+
1907+
18931908
class TestSetitemValidation:
18941909
# This is adapted from pandas/tests/arrays/masked/test_indexing.py
18951910
# but checks for warnings instead of errors.

pandas/tests/frame/indexing/test_set_value.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,7 @@ def test_set_value_resize(self, float_frame):
2626
assert float_frame._get_value("foobar", "qux") == 0
2727

2828
res = float_frame.copy()
29-
with tm.assert_produces_warning(
30-
FutureWarning, match="Setting an item of incompatible dtype"
31-
):
32-
res._set_value("foobar", "baz", "sam")
29+
res._set_value("foobar", "baz", "sam")
3330
assert res["baz"].dtype == np.object_
3431

3532
res = float_frame.copy()

0 commit comments

Comments
 (0)