Skip to content

Commit c09808b

Browse files
fix additional tests that were relying on chained assignment
1 parent be3e9fa commit c09808b

14 files changed

+88
-57
lines changed

pandas/tests/apply/test_frame_apply.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -347,7 +347,7 @@ def test_apply_yield_list(float_frame):
347347

348348

349349
def test_apply_reduce_Series(float_frame):
350-
float_frame["A"].iloc[::2] = np.nan
350+
float_frame.iloc[::2, float_frame.columns.get_loc("A")] = np.nan
351351
expected = float_frame.mean(1)
352352
result = float_frame.apply(np.mean, axis=1)
353353
tm.assert_series_equal(result, expected)

pandas/tests/frame/indexing/test_setitem.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1136,7 +1136,7 @@ def test_setitem_always_copy(self, float_frame, using_copy_on_write):
11361136
if using_copy_on_write:
11371137
with pytest.raises(ChainedAssignmentError):
11381138
float_frame["E"][5:10] = np.nan
1139-
float_frame.loc[5:10, "E"] = np.nan
1139+
float_frame.loc[float_frame.index[5] : float_frame.index[9], "E"] = np.nan
11401140
else:
11411141
float_frame["E"][5:10] = np.nan
11421142
assert notna(s[5:10]).all()

pandas/tests/frame/methods/test_cov_corr.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -107,9 +107,10 @@ class TestDataFrameCorr:
107107
@pytest.mark.parametrize("method", ["pearson", "kendall", "spearman"])
108108
@td.skip_if_no_scipy
109109
def test_corr_scipy_method(self, float_frame, method):
110-
float_frame["A"][:5] = np.nan
111-
float_frame["B"][5:10] = np.nan
112-
float_frame["A"][:10] = float_frame["A"][10:20]
110+
idx = float_frame.index
111+
float_frame.loc[: idx[4], "A"] = np.nan
112+
float_frame.loc[idx[5] : idx[9], "B"] = np.nan
113+
float_frame.loc[: idx[9], "A"] = float_frame["A"][10:20]
113114

114115
correls = float_frame.corr(method=method)
115116
expected = float_frame["A"].corr(float_frame["C"], method=method)

pandas/tests/frame/methods/test_fillna.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -392,16 +392,18 @@ def test_fillna_datetime_columns(self):
392392
tm.assert_frame_equal(result, expected)
393393

394394
def test_ffill(self, datetime_frame):
395-
datetime_frame["A"][:5] = np.nan
396-
datetime_frame["A"][-5:] = np.nan
395+
idx = datetime_frame.index
396+
datetime_frame.loc[: idx[4], "A"] = np.nan
397+
datetime_frame.loc[idx[-5] :, "A"] = np.nan
397398

398399
tm.assert_frame_equal(
399400
datetime_frame.ffill(), datetime_frame.fillna(method="ffill")
400401
)
401402

402403
def test_bfill(self, datetime_frame):
403-
datetime_frame["A"][:5] = np.nan
404-
datetime_frame["A"][-5:] = np.nan
404+
idx = datetime_frame.index
405+
datetime_frame.loc[: idx[4], "A"] = np.nan
406+
datetime_frame.loc[idx[-5] :, "A"] = np.nan
405407

406408
tm.assert_frame_equal(
407409
datetime_frame.bfill(), datetime_frame.fillna(method="bfill")
@@ -467,8 +469,8 @@ def test_fillna_integer_limit(self, type):
467469

468470
def test_fillna_inplace(self):
469471
df = DataFrame(np.random.randn(10, 4))
470-
df[1][:4] = np.nan
471-
df[3][-4:] = np.nan
472+
df.loc[:4, 1] = np.nan
473+
df.loc[-4:, 3] = np.nan
472474

473475
expected = df.fillna(value=0)
474476
assert expected is not df
@@ -479,8 +481,8 @@ def test_fillna_inplace(self):
479481
expected = df.fillna(value={0: 0}, inplace=True)
480482
assert expected is None
481483

482-
df[1][:4] = np.nan
483-
df[3][-4:] = np.nan
484+
df.loc[:4, 1] = np.nan
485+
df.loc[-4:, 3] = np.nan
484486
expected = df.fillna(method="ffill")
485487
assert expected is not df
486488

pandas/tests/frame/methods/test_rank.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,10 @@ def test_rank(self, float_frame):
4343
import scipy.stats # noqa:F401
4444
from scipy.stats import rankdata
4545

46-
float_frame["A"][::2] = np.nan
47-
float_frame["B"][::3] = np.nan
48-
float_frame["C"][::4] = np.nan
49-
float_frame["D"][::5] = np.nan
46+
float_frame.loc[::2, "A"] = np.nan
47+
float_frame.loc[::3, "B"] = np.nan
48+
float_frame.loc[::4, "C"] = np.nan
49+
float_frame.loc[::5, "D"] = np.nan
5050

5151
ranks0 = float_frame.rank()
5252
ranks1 = float_frame.rank(1)
@@ -148,10 +148,10 @@ def test_rank_na_option(self, float_frame):
148148
import scipy.stats # noqa:F401
149149
from scipy.stats import rankdata
150150

151-
float_frame["A"][::2] = np.nan
152-
float_frame["B"][::3] = np.nan
153-
float_frame["C"][::4] = np.nan
154-
float_frame["D"][::5] = np.nan
151+
float_frame.loc[::2, "A"] = np.nan
152+
float_frame.loc[::3, "B"] = np.nan
153+
float_frame.loc[::4, "C"] = np.nan
154+
float_frame.loc[::5, "D"] = np.nan
155155

156156
# bottom
157157
ranks0 = float_frame.rank(na_option="bottom")

pandas/tests/frame/methods/test_replace.py

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,9 @@ def mix_abc() -> dict[str, list[float | str]]:
2929

3030
class TestDataFrameReplace:
3131
def test_replace_inplace(self, datetime_frame, float_string_frame):
32-
datetime_frame["A"][:5] = np.nan
33-
datetime_frame["A"][-5:] = np.nan
32+
idx = datetime_frame.index
33+
datetime_frame.loc[: idx[4], "A"] = np.nan
34+
datetime_frame.loc[idx[-5] :, "A"] = np.nan
3435

3536
tsframe = datetime_frame.copy()
3637
return_value = tsframe.replace(np.nan, 0, inplace=True)
@@ -420,16 +421,17 @@ def test_regex_replace_string_types(
420421
tm.assert_equal(result, expected)
421422

422423
def test_replace(self, datetime_frame):
423-
datetime_frame["A"][:5] = np.nan
424-
datetime_frame["A"][-5:] = np.nan
424+
idx = datetime_frame.index
425+
datetime_frame.loc[: idx[4], "A"] = np.nan
426+
datetime_frame.loc[idx[-5] :, "A"] = np.nan
425427

426428
zero_filled = datetime_frame.replace(np.nan, -1e8)
427429
tm.assert_frame_equal(zero_filled, datetime_frame.fillna(-1e8))
428430
tm.assert_frame_equal(zero_filled.replace(-1e8, np.nan), datetime_frame)
429431

430-
datetime_frame["A"][:5] = np.nan
431-
datetime_frame["A"][-5:] = np.nan
432-
datetime_frame["B"][:5] = -1e8
432+
datetime_frame.loc[: idx[4], "A"] = np.nan
433+
datetime_frame.loc[idx[-5] :, "A"] = np.nan
434+
datetime_frame.loc[: idx[4], "B"] = -1e8
433435

434436
# empty
435437
df = DataFrame(index=["a", "b"])
@@ -716,16 +718,17 @@ def test_replace_for_new_dtypes(self, datetime_frame):
716718

717719
# dtypes
718720
tsframe = datetime_frame.copy().astype(np.float32)
719-
tsframe["A"][:5] = np.nan
720-
tsframe["A"][-5:] = np.nan
721+
idx = tsframe.index
722+
tsframe.loc[: idx[4], "A"] = np.nan
723+
tsframe.loc[idx[-5] :, "A"] = np.nan
721724

722725
zero_filled = tsframe.replace(np.nan, -1e8)
723726
tm.assert_frame_equal(zero_filled, tsframe.fillna(-1e8))
724727
tm.assert_frame_equal(zero_filled.replace(-1e8, np.nan), tsframe)
725728

726-
tsframe["A"][:5] = np.nan
727-
tsframe["A"][-5:] = np.nan
728-
tsframe["B"][:5] = -1e8
729+
tsframe.loc[: idx[4], "A"] = np.nan
730+
tsframe.loc[idx[-5] :, "A"] = np.nan
731+
tsframe.loc[: idx[4], "B"] = -1e8
729732

730733
b = tsframe["B"]
731734
b[b == -1e8] = np.nan

pandas/tests/frame/methods/test_sort_values.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -330,13 +330,20 @@ def test_sort_values_datetimes(self):
330330
df2 = df.sort_values(by=["C", "B"])
331331
tm.assert_frame_equal(df1, df2)
332332

333-
def test_sort_values_frame_column_inplace_sort_exception(self, float_frame):
333+
def test_sort_values_frame_column_inplace_sort_exception(
334+
self, float_frame, using_copy_on_write
335+
):
334336
s = float_frame["A"]
335-
with pytest.raises(ValueError, match="This Series is a view"):
337+
if using_copy_on_write:
338+
# with CoW, s is a new object detached from float_frame, so we can
339+
# actually modify it inplace
336340
s.sort_values(inplace=True)
341+
else:
342+
with pytest.raises(ValueError, match="This Series is a view"):
343+
s.sort_values(inplace=True)
337344

338-
cp = s.copy()
339-
cp.sort_values() # it works!
345+
cp = s.copy()
346+
cp.sort_values() # it works!
340347

341348
def test_sort_values_nat_values_in_int_column(self):
342349

pandas/tests/frame/methods/test_to_csv.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ def read_csv(self, path, **kwargs):
3535
def test_to_csv_from_csv1(self, float_frame, datetime_frame):
3636

3737
with tm.ensure_clean("__tmp_to_csv_from_csv1__") as path:
38-
float_frame["A"][:5] = np.nan
38+
float_frame.iloc[:5, float_frame.columns.get_loc("A")] = np.nan
3939

4040
float_frame.to_csv(path)
4141
float_frame.to_csv(path, columns=["A", "B"])

pandas/tests/frame/test_block_internals.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,10 @@
77
import numpy as np
88
import pytest
99

10-
from pandas.errors import PerformanceWarning
10+
from pandas.errors import (
11+
ChainedAssignmentError,
12+
PerformanceWarning,
13+
)
1114
import pandas.util._test_decorators as td
1215

1316
import pandas as pd
@@ -346,7 +349,11 @@ def test_stale_cached_series_bug_473(self, using_copy_on_write):
346349
)
347350
repr(Y)
348351
Y["e"] = Y["e"].astype("object")
349-
Y["g"]["c"] = np.NaN
352+
if using_copy_on_write:
353+
with pytest.raises(ChainedAssignmentError):
354+
Y["g"]["c"] = np.NaN
355+
else:
356+
Y["g"]["c"] = np.NaN
350357
repr(Y)
351358
result = Y.sum() # noqa
352359
exp = Y["g"].sum() # noqa

pandas/tests/frame/test_constructors.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -719,7 +719,8 @@ def test_constructor_defaultdict(self, float_frame):
719719
from collections import defaultdict
720720

721721
data = {}
722-
float_frame["B"][:10] = np.nan
722+
float_frame.loc[: float_frame.index[10], "B"] = np.nan
723+
723724
for k, v in float_frame.items():
724725
dct = defaultdict(dict)
725726
dct.update(v.to_dict())
@@ -2204,7 +2205,9 @@ def test_constructor_series_copy(self, float_frame):
22042205
series = float_frame._series
22052206

22062207
df = DataFrame({"A": series["A"]}, copy=True)
2207-
df["A"][:] = 5
2208+
# TODO can be replaced with `df.loc[:, "A"] = 5` after deprecation about
2209+
# inplace mutation is enforced
2210+
df.loc[df.index[0] : df.index[-1], "A"] = 5
22082211

22092212
assert not (series["A"] == 5).all()
22102213

pandas/tests/io/excel/test_writers.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -374,7 +374,7 @@ def test_excel_writer_context_manager(self, frame, path):
374374

375375
def test_roundtrip(self, frame, path):
376376
frame = frame.copy()
377-
frame["A"][:5] = np.nan
377+
frame.iloc[:5, frame.columns.get_loc("A")] = np.nan
378378

379379
frame.to_excel(path, "test1")
380380
frame.to_excel(path, "test1", columns=["A", "B"])
@@ -444,7 +444,7 @@ def test_ts_frame(self, tsframe, path):
444444

445445
def test_basics_with_nan(self, frame, path):
446446
frame = frame.copy()
447-
frame["A"][:5] = np.nan
447+
frame.iloc[:5, frame.columns.get_loc("A")] = np.nan
448448
frame.to_excel(path, "test1")
449449
frame.to_excel(path, "test1", columns=["A", "B"])
450450
frame.to_excel(path, "test1", header=False)
@@ -508,7 +508,7 @@ def test_sheets(self, frame, tsframe, path):
508508
tsframe.index = index
509509

510510
frame = frame.copy()
511-
frame["A"][:5] = np.nan
511+
frame.iloc[:5, frame.columns.get_loc("A")] = np.nan
512512

513513
frame.to_excel(path, "test1")
514514
frame.to_excel(path, "test1", columns=["A", "B"])
@@ -530,7 +530,7 @@ def test_sheets(self, frame, tsframe, path):
530530

531531
def test_colaliases(self, frame, path):
532532
frame = frame.copy()
533-
frame["A"][:5] = np.nan
533+
frame.iloc[:5, frame.columns.get_loc("A")] = np.nan
534534

535535
frame.to_excel(path, "test1")
536536
frame.to_excel(path, "test1", columns=["A", "B"])
@@ -548,7 +548,7 @@ def test_colaliases(self, frame, path):
548548

549549
def test_roundtrip_indexlabels(self, merge_cells, frame, path):
550550
frame = frame.copy()
551-
frame["A"][:5] = np.nan
551+
frame.iloc[:5, frame.columns.get_loc("A")] = np.nan
552552

553553
frame.to_excel(path, "test1")
554554
frame.to_excel(path, "test1", columns=["A", "B"])

pandas/tests/series/accessors/test_dt_accessor.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,10 @@
1212
import pytz
1313

1414
from pandas._libs.tslibs.timezones import maybe_get_tz
15-
from pandas.errors import SettingWithCopyError
15+
from pandas.errors import (
16+
ChainedAssignmentError,
17+
SettingWithCopyError,
18+
)
1619

1720
from pandas.core.dtypes.common import (
1821
is_integer_dtype,
@@ -287,8 +290,8 @@ def test_dt_accessor_not_writeable(self, using_copy_on_write):
287290
msg = "modifications to a property of a datetimelike.+not supported"
288291
with pd.option_context("chained_assignment", "raise"):
289292
if using_copy_on_write:
290-
# TODO(CoW) it would be nice to keep a warning/error for this case
291-
ser.dt.hour[0] = 5
293+
with pytest.raises(ChainedAssignmentError):
294+
ser.dt.hour[0] = 5
292295
else:
293296
with pytest.raises(SettingWithCopyError, match=msg):
294297
ser.dt.hour[0] = 5

pandas/tests/series/methods/test_rank.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ def test_rank(self, datetime_series):
4444
from scipy.stats import rankdata
4545

4646
datetime_series[::2] = np.nan
47-
datetime_series[:10][::3] = 4.0
47+
datetime_series[:10:3] = 4.0
4848

4949
ranks = datetime_series.rank()
5050
oranks = datetime_series.astype("O").rank()

pandas/tests/series/methods/test_sort_values.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111

1212
class TestSeriesSortValues:
13-
def test_sort_values(self, datetime_series):
13+
def test_sort_values(self, datetime_series, using_copy_on_write):
1414

1515
# check indexes are reordered corresponding with the values
1616
ser = Series([3, 2, 4, 1], ["A", "B", "C", "D"])
@@ -80,13 +80,18 @@ def test_sort_values(self, datetime_series):
8080
# Series.sort_values operating on a view
8181
df = DataFrame(np.random.randn(10, 4))
8282
s = df.iloc[:, 0]
83+
s_orig_sorted = s.copy().sort_values()
8384

84-
msg = (
85-
"This Series is a view of some other array, to sort in-place "
86-
"you must create a copy"
87-
)
88-
with pytest.raises(ValueError, match=msg):
85+
if using_copy_on_write:
8986
s.sort_values(inplace=True)
87+
tm.assert_series_equal(s, s_orig_sorted)
88+
else:
89+
msg = (
90+
"This Series is a view of some other array, to sort in-place "
91+
"you must create a copy"
92+
)
93+
with pytest.raises(ValueError, match=msg):
94+
s.sort_values(inplace=True)
9095

9196
def test_sort_values_categorical(self):
9297

0 commit comments

Comments
 (0)