Skip to content

Commit 9379c7b

Browse files
committed
enforce pdep6
1 parent c46fb76 commit 9379c7b

26 files changed

+218
-498
lines changed

doc/source/user_guide/categorical.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -793,7 +793,7 @@ Assigning a ``Categorical`` to parts of a column of other types will use the val
793793
:okwarning:
794794
795795
df = pd.DataFrame({"a": [1, 1, 1, 1, 1], "b": ["a", "a", "a", "a", "a"]})
796-
df.loc[1:2, "a"] = pd.Categorical(["b", "b"], categories=["a", "b"])
796+
df.loc[1:2, "a"] = pd.Categorical([2, 2], categories=[2, 3])
797797
df.loc[2:3, "b"] = pd.Categorical(["b", "b"], categories=["a", "b"])
798798
df
799799
df.dtypes

pandas/core/indexing.py

+4-10
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@
2525
)
2626
from pandas.errors.cow import _chained_assignment_msg
2727
from pandas.util._decorators import doc
28-
from pandas.util._exceptions import find_stack_level
2928

3029
from pandas.core.dtypes.cast import (
3130
can_hold_element,
@@ -2124,7 +2123,7 @@ def _setitem_single_column(self, loc: int, value, plane_indexer) -> None:
21242123
self.obj._mgr.column_setitem(
21252124
loc, plane_indexer, value, inplace_only=True
21262125
)
2127-
except (ValueError, TypeError, LossySetitemError):
2126+
except (ValueError, TypeError, LossySetitemError) as exc:
21282127
# If we're setting an entire column and we can't do it inplace,
21292128
# then we can use value's dtype (or inferred dtype)
21302129
# instead of object
@@ -2140,14 +2139,9 @@ def _setitem_single_column(self, loc: int, value, plane_indexer) -> None:
21402139
# - Exclude `object`, as then no upcasting happens.
21412140
# - Exclude empty initial object with enlargement,
21422141
# as then there's nothing to be inconsistent with.
2143-
warnings.warn(
2144-
f"Setting an item of incompatible dtype is deprecated "
2145-
"and will raise in a future error of pandas. "
2146-
f"Value '{value}' has dtype incompatible with {dtype}, "
2147-
"please explicitly cast to a compatible dtype first.",
2148-
FutureWarning,
2149-
stacklevel=find_stack_level(),
2150-
)
2142+
raise TypeError(
2143+
f"Invalid value '{value}' for dtype '{dtype}'"
2144+
) from exc
21512145
self.obj.isetitem(loc, value)
21522146
else:
21532147
# set value into the column (first attempting to operate inplace, then

pandas/core/internals/blocks.py

+1-8
Original file line numberDiff line numberDiff line change
@@ -467,14 +467,7 @@ def coerce_to_target_dtype(self, other, warn_on_upcast: bool = False) -> Block:
467467
warn_on_upcast = False
468468

469469
if warn_on_upcast:
470-
warnings.warn(
471-
f"Setting an item of incompatible dtype is deprecated "
472-
"and will raise an error in a future version of pandas. "
473-
f"Value '{other}' has dtype incompatible with {self.values.dtype}, "
474-
"please explicitly cast to a compatible dtype first.",
475-
FutureWarning,
476-
stacklevel=find_stack_level(),
477-
)
470+
raise TypeError(f"Invalid value '{other}' for dtype '{self.values.dtype}'")
478471
if self.values.dtype == new_dtype:
479472
raise AssertionError(
480473
f"Did not expect new dtype {new_dtype} to equal self.dtype "

pandas/tests/copy_view/test_indexing.py

+11-15
Original file line numberDiff line numberDiff line change
@@ -725,15 +725,13 @@ def test_column_as_series_set_with_upcast(backend):
725725
with pytest.raises(TypeError, match="Invalid value"):
726726
s[0] = "foo"
727727
expected = Series([1, 2, 3], name="a")
728+
tm.assert_series_equal(s, expected)
729+
tm.assert_frame_equal(df, df_orig)
730+
# ensure cached series on getitem is not the changed series
731+
tm.assert_series_equal(df["a"], df_orig["a"])
728732
else:
729-
with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):
733+
with pytest.raises(TypeError, match="Invalid value"):
730734
s[0] = "foo"
731-
expected = Series(["foo", 2, 3], dtype=object, name="a")
732-
733-
tm.assert_series_equal(s, expected)
734-
tm.assert_frame_equal(df, df_orig)
735-
# ensure cached series on getitem is not the changed series
736-
tm.assert_series_equal(df["a"], df_orig["a"])
737735

738736

739737
@pytest.mark.parametrize(
@@ -805,16 +803,14 @@ def test_set_value_copy_only_necessary_column(indexer_func, indexer, val, col):
805803
view = df[:]
806804

807805
if val == "a":
808-
with tm.assert_produces_warning(
809-
FutureWarning, match="Setting an item of incompatible dtype is deprecated"
810-
):
806+
with pytest.raises(TypeError, match="Invalid value"):
811807
indexer_func(df)[indexer] = val
808+
else:
809+
indexer_func(df)[indexer] = val
812810

813-
indexer_func(df)[indexer] = val
814-
815-
assert np.shares_memory(get_array(df, "b"), get_array(view, "b"))
816-
assert not np.shares_memory(get_array(df, "a"), get_array(view, "a"))
817-
tm.assert_frame_equal(view, df_orig)
811+
assert np.shares_memory(get_array(df, "b"), get_array(view, "b"))
812+
assert not np.shares_memory(get_array(df, "a"), get_array(view, "a"))
813+
tm.assert_frame_equal(view, df_orig)
818814

819815

820816
def test_series_midx_slice():

pandas/tests/copy_view/test_methods.py

+13-13
Original file line numberDiff line numberDiff line change
@@ -1105,26 +1105,26 @@ def test_putmask_aligns_rhs_no_reference(dtype):
11051105
assert np.shares_memory(arr_a, get_array(df, "a"))
11061106

11071107

1108-
@pytest.mark.parametrize(
1109-
"val, exp, warn", [(5.5, True, FutureWarning), (5, False, None)]
1110-
)
1111-
def test_putmask_dont_copy_some_blocks(val, exp, warn):
1108+
@pytest.mark.parametrize("val, exp, raises", [(5.5, True, True), (5, False, False)])
1109+
def test_putmask_dont_copy_some_blocks(val, exp, raises: bool):
11121110
df = DataFrame({"a": [1, 2], "b": 1, "c": 1.5})
11131111
view = df[:]
11141112
df_orig = df.copy()
11151113
indexer = DataFrame(
11161114
[[True, False, False], [True, False, False]], columns=list("abc")
11171115
)
1118-
with tm.assert_produces_warning(warn, match="incompatible dtype"):
1116+
if raises:
1117+
with pytest.raises(TypeError, match="Invalid value"):
1118+
df[indexer] = val
1119+
else:
11191120
df[indexer] = val
1120-
1121-
assert not np.shares_memory(get_array(view, "a"), get_array(df, "a"))
1122-
# TODO(CoW): Could split blocks to avoid copying the whole block
1123-
assert np.shares_memory(get_array(view, "b"), get_array(df, "b")) is exp
1124-
assert np.shares_memory(get_array(view, "c"), get_array(df, "c"))
1125-
assert df._mgr._has_no_reference(1) is not exp
1126-
assert not df._mgr._has_no_reference(2)
1127-
tm.assert_frame_equal(view, df_orig)
1121+
assert not np.shares_memory(get_array(view, "a"), get_array(df, "a"))
1122+
# TODO(CoW): Could split blocks to avoid copying the whole block
1123+
assert np.shares_memory(get_array(view, "b"), get_array(df, "b")) is exp
1124+
assert np.shares_memory(get_array(view, "c"), get_array(df, "c"))
1125+
assert df._mgr._has_no_reference(1) is not exp
1126+
assert not df._mgr._has_no_reference(2)
1127+
tm.assert_frame_equal(view, df_orig)
11281128

11291129

11301130
@pytest.mark.parametrize("dtype", ["int64", "Int64"])

pandas/tests/frame/indexing/test_coercion.py

+6-30
Original file line numberDiff line numberDiff line change
@@ -49,35 +49,19 @@ def test_loc_setitem_multiindex_columns(self, consolidate):
4949
def test_37477():
5050
# fixed by GH#45121
5151
orig = DataFrame({"A": [1, 2, 3], "B": [3, 4, 5]})
52-
expected = DataFrame({"A": [1, 2, 3], "B": [3, 1.2, 5]})
5352

5453
df = orig.copy()
55-
with tm.assert_produces_warning(
56-
FutureWarning, match="Setting an item of incompatible dtype"
57-
):
54+
with pytest.raises(TypeError, match="Invalid value"):
5855
df.at[1, "B"] = 1.2
59-
tm.assert_frame_equal(df, expected)
6056

61-
df = orig.copy()
62-
with tm.assert_produces_warning(
63-
FutureWarning, match="Setting an item of incompatible dtype"
64-
):
57+
with pytest.raises(TypeError, match="Invalid value"):
6558
df.loc[1, "B"] = 1.2
66-
tm.assert_frame_equal(df, expected)
6759

68-
df = orig.copy()
69-
with tm.assert_produces_warning(
70-
FutureWarning, match="Setting an item of incompatible dtype"
71-
):
60+
with pytest.raises(TypeError, match="Invalid value"):
7261
df.iat[1, 1] = 1.2
73-
tm.assert_frame_equal(df, expected)
7462

75-
df = orig.copy()
76-
with tm.assert_produces_warning(
77-
FutureWarning, match="Setting an item of incompatible dtype"
78-
):
63+
with pytest.raises(TypeError, match="Invalid value"):
7964
df.iloc[1, 1] = 1.2
80-
tm.assert_frame_equal(df, expected)
8165

8266

8367
def test_6942(indexer_al):
@@ -107,19 +91,11 @@ def test_26395(indexer_al):
10791
expected = DataFrame({"D": [0, 0, 2]}, index=["A", "B", "C"], dtype=np.int64)
10892
tm.assert_frame_equal(df, expected)
10993

110-
with tm.assert_produces_warning(
111-
FutureWarning, match="Setting an item of incompatible dtype"
112-
):
94+
with pytest.raises(TypeError, match="Invalid value"):
11395
indexer_al(df)["C", "D"] = 44.5
114-
expected = DataFrame({"D": [0, 0, 44.5]}, index=["A", "B", "C"], dtype=np.float64)
115-
tm.assert_frame_equal(df, expected)
11696

117-
with tm.assert_produces_warning(
118-
FutureWarning, match="Setting an item of incompatible dtype"
119-
):
97+
with pytest.raises(TypeError, match="Invalid value"):
12098
indexer_al(df)["C", "D"] = "hello"
121-
expected = DataFrame({"D": [0, 0, "hello"]}, index=["A", "B", "C"], dtype=object)
122-
tm.assert_frame_equal(df, expected)
12399

124100

125101
@pytest.mark.xfail(reason="unwanted upcast")

pandas/tests/frame/indexing/test_indexing.py

+23-63
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@
2525
Timestamp,
2626
date_range,
2727
isna,
28-
notna,
2928
to_datetime,
3029
)
3130
import pandas._testing as tm
@@ -833,13 +832,8 @@ def test_setitem_single_column_mixed_datetime(self):
833832
tm.assert_series_equal(result, expected)
834833

835834
# GH#16674 iNaT is treated as an integer when given by the user
836-
with tm.assert_produces_warning(
837-
FutureWarning, match="Setting an item of incompatible dtype"
838-
):
835+
with pytest.raises(TypeError, match="Invalid value"):
839836
df.loc["b", "timestamp"] = iNaT
840-
assert not isna(df.loc["b", "timestamp"])
841-
assert df["timestamp"].dtype == np.object_
842-
assert df.loc["b", "timestamp"] == iNaT
843837

844838
# allow this syntax (as of GH#3216)
845839
df.loc["c", "timestamp"] = np.nan
@@ -851,35 +845,11 @@ def test_setitem_single_column_mixed_datetime(self):
851845

852846
def test_setitem_mixed_datetime(self):
853847
# GH 9336
854-
expected = DataFrame(
855-
{
856-
"a": [0, 0, 0, 0, 13, 14],
857-
"b": [
858-
datetime(2012, 1, 1),
859-
1,
860-
"x",
861-
"y",
862-
datetime(2013, 1, 1),
863-
datetime(2014, 1, 1),
864-
],
865-
}
866-
)
867848
df = DataFrame(0, columns=list("ab"), index=range(6))
868849
df["b"] = pd.NaT
869850
df.loc[0, "b"] = datetime(2012, 1, 1)
870-
with tm.assert_produces_warning(
871-
FutureWarning, match="Setting an item of incompatible dtype"
872-
):
851+
with pytest.raises(TypeError, match="Invalid value"):
873852
df.loc[1, "b"] = 1
874-
df.loc[[2, 3], "b"] = "x", "y"
875-
A = np.array(
876-
[
877-
[13, np.datetime64("2013-01-01T00:00:00")],
878-
[14, np.datetime64("2014-01-01T00:00:00")],
879-
]
880-
)
881-
df.loc[[4, 5], ["a", "b"]] = A
882-
tm.assert_frame_equal(df, expected)
883853

884854
def test_setitem_frame_float(self, float_frame):
885855
piece = float_frame.loc[float_frame.index[:2], ["A", "B"]]
@@ -936,12 +906,8 @@ def test_setitem_frame_upcast(self):
936906
# needs upcasting
937907
df = DataFrame([[1, 2, "foo"], [3, 4, "bar"]], columns=["A", "B", "C"])
938908
df2 = df.copy()
939-
with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):
909+
with pytest.raises(TypeError, match="Invalid value"):
940910
df2.loc[:, ["A", "B"]] = df.loc[:, ["A", "B"]] + 0.5
941-
expected = df.reindex(columns=["A", "B"])
942-
expected += 0.5
943-
expected["C"] = df["C"]
944-
tm.assert_frame_equal(df2, expected)
945911

946912
def test_setitem_frame_align(self, float_frame):
947913
piece = float_frame.loc[float_frame.index[:2], ["A", "B"]]
@@ -1366,12 +1332,8 @@ def test_loc_setitem_rhs_frame(self, idxr, val):
13661332
# GH#47578
13671333
df = DataFrame({"a": [1, 2]})
13681334

1369-
with tm.assert_produces_warning(
1370-
FutureWarning, match="Setting an item of incompatible dtype"
1371-
):
1335+
with pytest.raises(TypeError, match="Invalid value"):
13721336
df.loc[:, idxr] = DataFrame({"a": [val, 11]}, index=[1, 2])
1373-
expected = DataFrame({"a": [np.nan, val]})
1374-
tm.assert_frame_equal(df, expected)
13751337

13761338
def test_iloc_setitem_enlarge_no_warning(self):
13771339
# GH#47381
@@ -1579,18 +1541,9 @@ def test_setitem(self):
15791541
# With NaN: because uint64 has no NaN element,
15801542
# the column should be cast to object.
15811543
df2 = df.copy()
1582-
with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):
1544+
with pytest.raises(TypeError, match="Invalid value"):
15831545
df2.iloc[1, 1] = pd.NaT
15841546
df2.iloc[1, 2] = pd.NaT
1585-
result = df2["B"]
1586-
tm.assert_series_equal(notna(result), Series([True, False, True], name="B"))
1587-
tm.assert_series_equal(
1588-
df2.dtypes,
1589-
Series(
1590-
[np.dtype("uint64"), np.dtype("O"), np.dtype("O")],
1591-
index=["A", "B", "C"],
1592-
),
1593-
)
15941547

15951548

15961549
def test_object_casting_indexing_wraps_datetimelike():
@@ -1926,22 +1879,30 @@ def test_add_new_column_infer_string():
19261879
class TestSetitemValidation:
19271880
# This is adapted from pandas/tests/arrays/masked/test_indexing.py
19281881
# but checks for warnings instead of errors.
1929-
def _check_setitem_invalid(self, df, invalid, indexer, warn):
1930-
msg = "Setting an item of incompatible dtype is deprecated"
1931-
msg = re.escape(msg)
1932-
1882+
def _check_setitem_invalid(self, df, invalid, indexer):
19331883
orig_df = df.copy()
19341884

19351885
# iloc
1936-
with tm.assert_produces_warning(warn, match=msg):
1886+
with pytest.raises(TypeError, match="Invalid value"):
19371887
df.iloc[indexer, 0] = invalid
19381888
df = orig_df.copy()
19391889

19401890
# loc
1941-
with tm.assert_produces_warning(warn, match=msg):
1891+
with pytest.raises(TypeError, match="Invalid value"):
19421892
df.loc[indexer, "a"] = invalid
19431893
df = orig_df.copy()
19441894

1895+
def _check_setitem_valid(self, df, value, indexer):
1896+
orig_df = df.copy()
1897+
1898+
# iloc
1899+
df.iloc[indexer, 0] = value
1900+
df = orig_df.copy()
1901+
1902+
# loc
1903+
df.loc[indexer, "a"] = value
1904+
df = orig_df.copy()
1905+
19451906
_invalid_scalars = [
19461907
1 + 2j,
19471908
"True",
@@ -1959,20 +1920,19 @@ def _check_setitem_invalid(self, df, invalid, indexer, warn):
19591920
@pytest.mark.parametrize("indexer", _indexers)
19601921
def test_setitem_validation_scalar_bool(self, invalid, indexer):
19611922
df = DataFrame({"a": [True, False, False]}, dtype="bool")
1962-
self._check_setitem_invalid(df, invalid, indexer, FutureWarning)
1923+
self._check_setitem_invalid(df, invalid, indexer)
19631924

19641925
@pytest.mark.parametrize("invalid", _invalid_scalars + [True, 1.5, np.float64(1.5)])
19651926
@pytest.mark.parametrize("indexer", _indexers)
19661927
def test_setitem_validation_scalar_int(self, invalid, any_int_numpy_dtype, indexer):
19671928
df = DataFrame({"a": [1, 2, 3]}, dtype=any_int_numpy_dtype)
19681929
if isna(invalid) and invalid is not pd.NaT and not np.isnat(invalid):
1969-
warn = None
1930+
self._check_setitem_valid(df, invalid, indexer)
19701931
else:
1971-
warn = FutureWarning
1972-
self._check_setitem_invalid(df, invalid, indexer, warn)
1932+
self._check_setitem_invalid(df, invalid, indexer)
19731933

19741934
@pytest.mark.parametrize("invalid", _invalid_scalars + [True])
19751935
@pytest.mark.parametrize("indexer", _indexers)
19761936
def test_setitem_validation_scalar_float(self, invalid, float_numpy_dtype, indexer):
19771937
df = DataFrame({"a": [1, 2, None]}, dtype=float_numpy_dtype)
1978-
self._check_setitem_invalid(df, invalid, indexer, FutureWarning)
1938+
self._check_setitem_invalid(df, invalid, indexer)

0 commit comments

Comments
 (0)