hyb
2026-01-30 44480e71b27aa9d4cb8441f50c873f1b110e9691
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
import numpy as np
import pytest
 
from pandas.compat import (
    PY311,
    WARNING_CHECK_DISABLED,
)
from pandas.errors import (
    ChainedAssignmentError,
    SettingWithCopyWarning,
)
 
from pandas import (
    DataFrame,
    option_context,
)
import pandas._testing as tm
 
 
def test_methods_iloc_warn(using_copy_on_write):
    if not using_copy_on_write:
        df = DataFrame({"a": [1, 2, 3], "b": 1})
        with tm.assert_cow_warning(match="A value"):
            df.iloc[:, 0].replace(1, 5, inplace=True)
 
        with tm.assert_cow_warning(match="A value"):
            df.iloc[:, 0].fillna(1, inplace=True)
 
        with tm.assert_cow_warning(match="A value"):
            df.iloc[:, 0].interpolate(inplace=True)
 
        with tm.assert_cow_warning(match="A value"):
            df.iloc[:, 0].ffill(inplace=True)
 
        with tm.assert_cow_warning(match="A value"):
            df.iloc[:, 0].bfill(inplace=True)
 
 
@pytest.mark.parametrize(
    "func, args",
    [
        ("replace", (4, 5)),
        ("fillna", (1,)),
        ("interpolate", ()),
        ("bfill", ()),
        ("ffill", ()),
    ],
)
def test_methods_iloc_getitem_item_cache(
    func, args, using_copy_on_write, warn_copy_on_write
):
    # ensure we don't incorrectly raise chained assignment warning because
    # of the item cache / iloc not setting the item cache
    df_orig = DataFrame({"a": [1, 2, 3], "b": 1})
 
    df = df_orig.copy()
    ser = df.iloc[:, 0]
    getattr(ser, func)(*args, inplace=True)
 
    # parent that holds item_cache is dead, so don't increase ref count
    df = df_orig.copy()
    ser = df.copy()["a"]
    getattr(ser, func)(*args, inplace=True)
 
    df = df_orig.copy()
    df["a"]  # populate the item_cache
    ser = df.iloc[:, 0]  # iloc creates a new object
    getattr(ser, func)(*args, inplace=True)
 
    df = df_orig.copy()
    df["a"]  # populate the item_cache
    ser = df["a"]
    getattr(ser, func)(*args, inplace=True)
 
    df = df_orig.copy()
    df["a"]  # populate the item_cache
    # TODO(CoW-warn) because of the usage of *args, this doesn't warn on Py3.11+
    if using_copy_on_write:
        with tm.raises_chained_assignment_error(not PY311):
            getattr(df["a"], func)(*args, inplace=True)
    else:
        with tm.assert_cow_warning(not PY311, match="A value"):
            getattr(df["a"], func)(*args, inplace=True)
 
    df = df_orig.copy()
    ser = df["a"]  # populate the item_cache and keep ref
    if using_copy_on_write:
        with tm.raises_chained_assignment_error(not PY311):
            getattr(df["a"], func)(*args, inplace=True)
    else:
        # ideally also warns on the default mode, but the ser' _cacher
        # messes up the refcount + even in warning mode this doesn't trigger
        # the warning of Py3.1+ (see above)
        with tm.assert_cow_warning(warn_copy_on_write and not PY311, match="A value"):
            getattr(df["a"], func)(*args, inplace=True)
 
 
def test_methods_iloc_getitem_item_cache_fillna(
    using_copy_on_write, warn_copy_on_write
):
    # ensure we don't incorrectly raise chained assignment warning because
    # of the item cache / iloc not setting the item cache
    df_orig = DataFrame({"a": [1, 2, 3], "b": 1})
 
    df = df_orig.copy()
    ser = df.iloc[:, 0]
    ser.fillna(1, inplace=True)
 
    # parent that holds item_cache is dead, so don't increase ref count
    df = df_orig.copy()
    ser = df.copy()["a"]
    ser.fillna(1, inplace=True)
 
    df = df_orig.copy()
    df["a"]  # populate the item_cache
    ser = df.iloc[:, 0]  # iloc creates a new object
    ser.fillna(1, inplace=True)
 
    df = df_orig.copy()
    df["a"]  # populate the item_cache
    ser = df["a"]
    ser.fillna(1, inplace=True)
 
    df = df_orig.copy()
    df["a"]  # populate the item_cache
    if using_copy_on_write:
        with tm.raises_chained_assignment_error():
            df["a"].fillna(1, inplace=True)
    else:
        with tm.assert_cow_warning(match="A value"):
            df["a"].fillna(1, inplace=True)
 
    df = df_orig.copy()
    ser = df["a"]  # populate the item_cache and keep ref
    if using_copy_on_write:
        with tm.raises_chained_assignment_error():
            df["a"].fillna(1, inplace=True)
    else:
        # TODO(CoW-warn) ideally also warns on the default mode, but the ser' _cacher
        # messes up the refcount
        with tm.assert_cow_warning(warn_copy_on_write, match="A value"):
            df["a"].fillna(1, inplace=True)
 
 
# TODO(CoW-warn) expand the cases
@pytest.mark.parametrize(
    "indexer", [0, [0, 1], slice(0, 2), np.array([True, False, True])]
)
def test_series_setitem(indexer, using_copy_on_write, warn_copy_on_write):
    # ensure we only get a single warning for those typical cases of chained
    # assignment
    df = DataFrame({"a": [1, 2, 3], "b": 1})
 
    # using custom check instead of tm.assert_produces_warning because that doesn't
    # fail if multiple warnings are raised
    if WARNING_CHECK_DISABLED:
        return
 
    with pytest.warns() as record:
        df["a"][indexer] = 0
    assert len(record) == 1
    if using_copy_on_write:
        assert record[0].category == ChainedAssignmentError
    else:
        assert record[0].category == FutureWarning
        assert "ChainedAssignmentError" in record[0].message.args[0]
 
 
@pytest.mark.filterwarnings("ignore::pandas.errors.SettingWithCopyWarning")
@pytest.mark.parametrize(
    "indexer", ["a", ["a", "b"], slice(0, 2), np.array([True, False, True])]
)
def test_frame_setitem(indexer, using_copy_on_write):
    df = DataFrame({"a": [1, 2, 3, 4, 5], "b": 1})
 
    extra_warnings = () if using_copy_on_write else (SettingWithCopyWarning,)
 
    with option_context("chained_assignment", "warn"):
        with tm.raises_chained_assignment_error(extra_warnings=extra_warnings):
            df[0:3][indexer] = 10
 
 
@pytest.mark.parametrize(
    "indexer", [0, [0, 1], slice(0, 2), np.array([True, False, True])]
)
def test_series_iloc_setitem(indexer):
    df = DataFrame({"a": [1, 2, 3], "b": 1})
 
    with option_context("chained_assignment", "warn"):
        with tm.raises_chained_assignment_error():
            df["a"].iloc[indexer] = 0
 
 
@pytest.mark.parametrize(
    "indexer", [0, [0, 1], slice(0, 2), np.array([True, False, True])]
)
def test_frame_iloc_setitem(indexer, using_copy_on_write):
    df = DataFrame({"a": [1, 2, 3, 4, 5], "b": 1})
 
    extra_warnings = () if using_copy_on_write else (SettingWithCopyWarning,)
 
    with option_context("chained_assignment", "warn"):
        with tm.raises_chained_assignment_error(extra_warnings=extra_warnings):
            df[0:3].iloc[indexer] = 10
 
 
@pytest.mark.parametrize(
    "indexer", [0, [0, 1], slice(0, 2), np.array([True, False, True])]
)
def test_series_loc_setitem(indexer):
    df = DataFrame({"a": [1, 2, 3], "b": 1})
 
    with option_context("chained_assignment", "warn"):
        with tm.raises_chained_assignment_error():
            df["a"].loc[indexer] = 0
 
 
@pytest.mark.parametrize(
    "indexer", [0, [0, 1], (0, "a"), slice(0, 2), np.array([True, False, True])]
)
def test_frame_loc_setitem(indexer, using_copy_on_write):
    df = DataFrame({"a": [1, 2, 3, 4, 5], "b": 1})
 
    extra_warnings = () if using_copy_on_write else (SettingWithCopyWarning,)
 
    with option_context("chained_assignment", "warn"):
        with tm.raises_chained_assignment_error(extra_warnings=extra_warnings):
            df[0:3].loc[indexer] = 10
 
 
def test_series_at_setitem():
    df = DataFrame({"a": [1, 2, 3], "b": 1})
 
    with option_context("chained_assignment", "warn"):
        with tm.raises_chained_assignment_error():
            df["a"].at[0] = 0
 
 
def test_frame_at_setitem():
    df = DataFrame({"a": [1, 2, 3, 4, 5], "b": 1})
 
    with option_context("chained_assignment", "warn"):
        with tm.raises_chained_assignment_error():
            df[0:3].at[0, "a"] = 10
 
 
def test_series_iat_setitem():
    df = DataFrame({"a": [1, 2, 3], "b": 1})
 
    with option_context("chained_assignment", "warn"):
        with tm.raises_chained_assignment_error():
            df["a"].iat[0] = 0
 
 
def test_frame_iat_setitem():
    df = DataFrame({"a": [1, 2, 3, 4, 5], "b": 1})
 
    with option_context("chained_assignment", "warn"):
        with tm.raises_chained_assignment_error():
            df[0:3].iat[0, 0] = 10