Skip to content

Commit c545701

Browse files
authored
TST: collect indexing tests by method (#40011)
1 parent b761848 commit c545701

11 files changed

+418
-489
lines changed

pandas/tests/frame/methods/test_update.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,3 +137,12 @@ def test_update_datetime_tz(self):
137137
result.update(result)
138138
expected = DataFrame([pd.Timestamp("2019", tz="UTC")])
139139
tm.assert_frame_equal(result, expected)
140+
141+
def test_update_with_different_dtype(self):
142+
# GH#3217
143+
df = DataFrame({"a": [1, 3], "b": [np.nan, 2]})
144+
df["c"] = np.nan
145+
df["c"].update(Series(["foo"], index=[0]))
146+
147+
expected = DataFrame({"a": [1, 3], "b": [np.nan, 2], "c": ["foo", np.nan]})
148+
tm.assert_frame_equal(df, expected)

pandas/tests/indexing/test_chaining_and_caching.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -457,3 +457,19 @@ def test_cache_updating2(self):
457457
tm.assert_frame_equal(df, expected)
458458
expected = Series([0, 0, 0, 2, 0], name="f")
459459
tm.assert_series_equal(df.f, expected)
460+
461+
def test_iloc_setitem_chained_assignment(self):
462+
# GH#3970
463+
with option_context("chained_assignment", None):
464+
df = DataFrame({"aa": range(5), "bb": [2.2] * 5})
465+
df["cc"] = 0.0
466+
467+
ck = [True] * len(df)
468+
469+
df["bb"].iloc[0] = 0.13
470+
471+
# TODO: unused
472+
df_tmp = df.iloc[ck] # noqa
473+
474+
df["bb"].iloc[0] = 0.15
475+
assert df["bb"].iloc[0] == 0.15

pandas/tests/indexing/test_datetime.py

Lines changed: 0 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,3 @@
1-
import numpy as np
2-
import pytest
3-
41
import pandas as pd
52
from pandas import (
63
DataFrame,
@@ -55,28 +52,6 @@ def test_indexing_fast_xs(self):
5552
expected = df.iloc[4:]
5653
tm.assert_frame_equal(result, expected)
5754

58-
def test_setitem_with_expansion(self):
59-
# indexing - setting an element
60-
df = DataFrame(
61-
data=pd.to_datetime(["2015-03-30 20:12:32", "2015-03-12 00:11:11"]),
62-
columns=["time"],
63-
)
64-
df["new_col"] = ["new", "old"]
65-
df.time = df.set_index("time").index.tz_localize("UTC")
66-
v = df[df.new_col == "new"].set_index("time").index.tz_convert("US/Pacific")
67-
68-
# trying to set a single element on a part of a different timezone
69-
# this converts to object
70-
df2 = df.copy()
71-
df2.loc[df2.new_col == "new", "time"] = v
72-
73-
expected = Series([v[0], df.loc[1, "time"]], name="time")
74-
tm.assert_series_equal(df2.time, expected)
75-
76-
v = df.loc[df.new_col == "new", "time"] + pd.Timedelta("1s")
77-
df.loc[df.new_col == "new", "time"] = v
78-
tm.assert_series_equal(df.loc[df.new_col == "new", "time"], v)
79-
8055
def test_consistency_with_tz_aware_scalar(self):
8156
# xef gh-12938
8257
# various ways of indexing the same tz-aware scalar
@@ -163,48 +138,6 @@ def test_indexing_with_datetimeindex_tz(self):
163138
expected = Series([0, 5], index=index)
164139
tm.assert_series_equal(result, expected)
165140

166-
@pytest.mark.parametrize("to_period", [True, False])
167-
def test_loc_getitem_listlike_of_datetimelike_keys(self, to_period):
168-
# GH 11497
169-
170-
idx = date_range("2011-01-01", "2011-01-02", freq="D", name="idx")
171-
if to_period:
172-
idx = idx.to_period("D")
173-
ser = Series([0.1, 0.2], index=idx, name="s")
174-
175-
keys = [Timestamp("2011-01-01"), Timestamp("2011-01-02")]
176-
if to_period:
177-
keys = [x.to_period("D") for x in keys]
178-
result = ser.loc[keys]
179-
exp = Series([0.1, 0.2], index=idx, name="s")
180-
if not to_period:
181-
exp.index = exp.index._with_freq(None)
182-
tm.assert_series_equal(result, exp, check_index_type=True)
183-
184-
keys = [
185-
Timestamp("2011-01-02"),
186-
Timestamp("2011-01-02"),
187-
Timestamp("2011-01-01"),
188-
]
189-
if to_period:
190-
keys = [x.to_period("D") for x in keys]
191-
exp = Series(
192-
[0.2, 0.2, 0.1], index=Index(keys, name="idx", dtype=idx.dtype), name="s"
193-
)
194-
result = ser.loc[keys]
195-
tm.assert_series_equal(result, exp, check_index_type=True)
196-
197-
keys = [
198-
Timestamp("2011-01-03"),
199-
Timestamp("2011-01-02"),
200-
Timestamp("2011-01-03"),
201-
]
202-
if to_period:
203-
keys = [x.to_period("D") for x in keys]
204-
205-
with pytest.raises(KeyError, match="with any missing labels"):
206-
ser.loc[keys]
207-
208141
def test_nanosecond_getitem_setitem_with_tz(self):
209142
# GH 11679
210143
data = ["2016-06-28 08:30:00.123456789"]
@@ -219,24 +152,6 @@ def test_nanosecond_getitem_setitem_with_tz(self):
219152
expected = DataFrame(-1, index=index, columns=["a"])
220153
tm.assert_frame_equal(result, expected)
221154

222-
def test_loc_setitem_with_expansion_and_existing_dst(self):
223-
# GH 18308
224-
start = Timestamp("2017-10-29 00:00:00+0200", tz="Europe/Madrid")
225-
end = Timestamp("2017-10-29 03:00:00+0100", tz="Europe/Madrid")
226-
ts = Timestamp("2016-10-10 03:00:00", tz="Europe/Madrid")
227-
idx = pd.date_range(start, end, closed="left", freq="H")
228-
assert ts not in idx # i.e. result.loc setitem is with-expansion
229-
230-
result = DataFrame(index=idx, columns=["value"])
231-
result.loc[ts, "value"] = 12
232-
expected = DataFrame(
233-
[np.nan] * len(idx) + [12],
234-
index=idx.append(pd.DatetimeIndex([ts])),
235-
columns=["value"],
236-
dtype=object,
237-
)
238-
tm.assert_frame_equal(result, expected)
239-
240155
def test_getitem_millisecond_resolution(self, frame_or_series):
241156
# GH#33589
242157

pandas/tests/indexing/test_floats.py

Lines changed: 52 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ def check(self, result, original, indexer, getitem):
5050
tm.makePeriodIndex,
5151
],
5252
)
53-
def test_scalar_non_numeric(self, index_func, frame_or_series):
53+
def test_scalar_non_numeric(self, index_func, frame_or_series, indexer_sl):
5454

5555
# GH 4892
5656
# float_indexers should raise exceptions
@@ -61,10 +61,7 @@ def test_scalar_non_numeric(self, index_func, frame_or_series):
6161

6262
# getting
6363
with pytest.raises(KeyError, match="^3.0$"):
64-
s[3.0]
65-
66-
with pytest.raises(KeyError, match="^3.0$"):
67-
s.loc[3.0]
64+
indexer_sl(s)[3.0]
6865

6966
# contains
7067
assert 3.0 not in s
@@ -88,11 +85,7 @@ def test_scalar_non_numeric(self, index_func, frame_or_series):
8885
else:
8986

9087
s2 = s.copy()
91-
s2.loc[3.0] = 10
92-
assert s2.index.is_object()
93-
94-
s2 = s.copy()
95-
s2[3.0] = 0
88+
indexer_sl(s2)[3.0] = 10
9689
assert s2.index.is_object()
9790

9891
@pytest.mark.parametrize(
@@ -114,44 +107,44 @@ def test_scalar_non_numeric_series_fallback(self, index_func):
114107
with pytest.raises(KeyError, match="^3.0$"):
115108
s[3.0]
116109

117-
def test_scalar_with_mixed(self):
110+
def test_scalar_with_mixed(self, indexer_sl):
118111

119112
s2 = Series([1, 2, 3], index=["a", "b", "c"])
120113
s3 = Series([1, 2, 3], index=["a", "b", 1.5])
121114

122115
# lookup in a pure string index with an invalid indexer
123116

124117
with pytest.raises(KeyError, match="^1.0$"):
125-
s2[1.0]
118+
indexer_sl(s2)[1.0]
126119

127120
with pytest.raises(KeyError, match=r"^1\.0$"):
128-
s2.loc[1.0]
121+
indexer_sl(s2)[1.0]
129122

130-
result = s2.loc["b"]
123+
result = indexer_sl(s2)["b"]
131124
expected = 2
132125
assert result == expected
133126

134127
# mixed index so we have label
135128
# indexing
136129
with pytest.raises(KeyError, match="^1.0$"):
137-
s3[1.0]
130+
indexer_sl(s3)[1.0]
138131

139-
result = s3[1]
140-
expected = 2
141-
assert result == expected
132+
if indexer_sl is not tm.loc:
133+
# __getitem__ falls back to positional
134+
result = s3[1]
135+
expected = 2
136+
assert result == expected
142137

143138
with pytest.raises(KeyError, match=r"^1\.0$"):
144-
s3.loc[1.0]
139+
indexer_sl(s3)[1.0]
145140

146-
result = s3.loc[1.5]
141+
result = indexer_sl(s3)[1.5]
147142
expected = 3
148143
assert result == expected
149144

150-
@pytest.mark.parametrize(
151-
"idxr,getitem", [(lambda x: x.loc, False), (lambda x: x, True)]
152-
)
153145
@pytest.mark.parametrize("index_func", [tm.makeIntIndex, tm.makeRangeIndex])
154-
def test_scalar_integer(self, index_func, frame_or_series, idxr, getitem):
146+
def test_scalar_integer(self, index_func, frame_or_series, indexer_sl):
147+
getitem = indexer_sl is not tm.loc
155148

156149
# test how scalar float indexers work on int indexes
157150

@@ -161,7 +154,7 @@ def test_scalar_integer(self, index_func, frame_or_series, idxr, getitem):
161154

162155
# coerce to equal int
163156

164-
result = idxr(obj)[3.0]
157+
result = indexer_sl(obj)[3.0]
165158
self.check(result, obj, 3, getitem)
166159

167160
if isinstance(obj, Series):
@@ -178,12 +171,12 @@ def compare(x, y):
178171
expected = Series(100.0, index=range(len(obj)), name=3)
179172

180173
s2 = obj.copy()
181-
idxr(s2)[3.0] = 100
174+
indexer_sl(s2)[3.0] = 100
182175

183-
result = idxr(s2)[3.0]
176+
result = indexer_sl(s2)[3.0]
184177
compare(result, expected)
185178

186-
result = idxr(s2)[3]
179+
result = indexer_sl(s2)[3]
187180
compare(result, expected)
188181

189182
@pytest.mark.parametrize("index_func", [tm.makeIntIndex, tm.makeRangeIndex])
@@ -204,7 +197,8 @@ def test_scalar_float(self, frame_or_series):
204197

205198
# assert all operations except for iloc are ok
206199
indexer = index[3]
207-
for idxr, getitem in [(lambda x: x.loc, False), (lambda x: x, True)]:
200+
for idxr in [tm.loc, tm.setitem]:
201+
getitem = idxr is not tm.loc
208202

209203
# getting
210204
result = idxr(s)[indexer]
@@ -242,7 +236,7 @@ def test_scalar_float(self, frame_or_series):
242236
],
243237
)
244238
@pytest.mark.parametrize("idx", [slice(3.0, 4), slice(3, 4.0), slice(3.0, 4.0)])
245-
def test_slice_non_numeric(self, index_func, idx, frame_or_series):
239+
def test_slice_non_numeric(self, index_func, idx, frame_or_series, indexer_sli):
246240

247241
# GH 4892
248242
# float_indexers should raise exceptions
@@ -252,38 +246,28 @@ def test_slice_non_numeric(self, index_func, idx, frame_or_series):
252246
s = gen_obj(frame_or_series, index)
253247

254248
# getitem
255-
msg = (
256-
"cannot do positional indexing "
257-
fr"on {type(index).__name__} with these indexers \[(3|4)\.0\] of "
258-
"type float"
259-
)
249+
if indexer_sli is tm.iloc:
250+
msg = (
251+
"cannot do positional indexing "
252+
fr"on {type(index).__name__} with these indexers \[(3|4)\.0\] of "
253+
"type float"
254+
)
255+
else:
256+
msg = (
257+
"cannot do slice indexing "
258+
fr"on {type(index).__name__} with these indexers "
259+
r"\[(3|4)(\.0)?\] "
260+
r"of type (float|int)"
261+
)
260262
with pytest.raises(TypeError, match=msg):
261-
s.iloc[idx]
262-
263-
msg = (
264-
"cannot do (slice|positional) indexing "
265-
fr"on {type(index).__name__} with these indexers "
266-
r"\[(3|4)(\.0)?\] "
267-
r"of type (float|int)"
268-
)
269-
for idxr in [lambda x: x.loc, lambda x: x.iloc, lambda x: x]:
270-
with pytest.raises(TypeError, match=msg):
271-
idxr(s)[idx]
263+
indexer_sli(s)[idx]
272264

273265
# setitem
274-
msg = "slice indices must be integers or None or have an __index__ method"
266+
if indexer_sli is tm.iloc:
267+
# otherwise we keep the same message as above
268+
msg = "slice indices must be integers or None or have an __index__ method"
275269
with pytest.raises(TypeError, match=msg):
276-
s.iloc[idx] = 0
277-
278-
msg = (
279-
"cannot do (slice|positional) indexing "
280-
fr"on {type(index).__name__} with these indexers "
281-
r"\[(3|4)(\.0)?\] "
282-
r"of type (float|int)"
283-
)
284-
for idxr in [lambda x: x.loc, lambda x: x]:
285-
with pytest.raises(TypeError, match=msg):
286-
idxr(s)[idx] = 0
270+
indexer_sli(s)[idx] = 0
287271

288272
def test_slice_integer(self):
289273

@@ -469,25 +453,24 @@ def test_float_slice_getitem_with_integer_index_raises(self, idx, index_func):
469453
s[idx]
470454

471455
@pytest.mark.parametrize("idx", [slice(3.0, 4), slice(3, 4.0), slice(3.0, 4.0)])
472-
def test_slice_float(self, idx, frame_or_series):
456+
def test_slice_float(self, idx, frame_or_series, indexer_sl):
473457

474458
# same as above, but for floats
475459
index = Index(np.arange(5.0)) + 0.1
476460
s = gen_obj(frame_or_series, index)
477461

478462
expected = s.iloc[3:4]
479-
for idxr in [lambda x: x.loc, lambda x: x]:
480463

481-
# getitem
482-
result = idxr(s)[idx]
483-
assert isinstance(result, type(s))
484-
tm.assert_equal(result, expected)
464+
# getitem
465+
result = indexer_sl(s)[idx]
466+
assert isinstance(result, type(s))
467+
tm.assert_equal(result, expected)
485468

486-
# setitem
487-
s2 = s.copy()
488-
idxr(s2)[idx] = 0
489-
result = idxr(s2)[idx].values.ravel()
490-
assert (result == 0).all()
469+
# setitem
470+
s2 = s.copy()
471+
indexer_sl(s2)[idx] = 0
472+
result = indexer_sl(s2)[idx].values.ravel()
473+
assert (result == 0).all()
491474

492475
def test_floating_index_doc_example(self):
493476

@@ -564,19 +547,6 @@ def test_floating_misc(self, indexer_sl):
564547
result = indexer_sl(s)[[2.5]]
565548
tm.assert_series_equal(result, Series([1], index=[2.5]))
566549

567-
def test_floating_tuples(self):
568-
# see gh-13509
569-
s = Series([(1, 1), (2, 2), (3, 3)], index=[0.0, 0.1, 0.2], name="foo")
570-
571-
result = s[0.0]
572-
assert result == (1, 1)
573-
574-
expected = Series([(1, 1), (2, 2)], index=[0.0, 0.0], name="foo")
575-
s = Series([(1, 1), (2, 2), (3, 3)], index=[0.0, 0.0, 0.2], name="foo")
576-
577-
result = s[0.0]
578-
tm.assert_series_equal(result, expected)
579-
580550
def test_float64index_slicing_bug(self):
581551
# GH 5557, related to slicing a float index
582552
ser = {

0 commit comments

Comments
 (0)