Skip to content

Commit 4c84e12

Browse files
authored
TST/REF: collect indexing tests by method (pandas-dev#38005)
1 parent 52a1725 commit 4c84e12

File tree

11 files changed

+166
-175
lines changed

11 files changed

+166
-175
lines changed

pandas/tests/frame/indexing/test_getitem.py

+12
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,18 @@ def test_getitem_sparse_column_return_type_and_dtype(self):
6868
tm.assert_series_equal(result, expected)
6969

7070

71+
class TestGetitemListLike:
72+
def test_getitem_list_missing_key(self):
73+
# GH#13822, incorrect error string with non-unique columns when missing
74+
# column is accessed
75+
df = DataFrame({"x": [1.0], "y": [2.0], "z": [3.0]})
76+
df.columns = ["x", "x", "z"]
77+
78+
# Check that we get the correct value in the KeyError
79+
with pytest.raises(KeyError, match=r"\['y'\] not in index"):
80+
df[["x", "y", "z"]]
81+
82+
7183
class TestGetitemCallable:
7284
def test_getitem_callable(self, float_frame):
7385
# GH#12533

pandas/tests/indexing/test_at.py

+11-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import numpy as np
44
import pytest
55

6-
from pandas import DataFrame, Series
6+
from pandas import DataFrame, Series, Timestamp
77
import pandas._testing as tm
88

99

@@ -27,6 +27,16 @@ def test_at_setitem_mixed_index_assignment(self):
2727
assert ser.iat[3] == 22
2828

2929

30+
class TestAtSetItemWithExpansion:
31+
def test_at_setitem_expansion_series_dt64tz_value(self, tz_naive_fixture):
32+
# GH#25506
33+
ts = Timestamp("2017-08-05 00:00:00+0100", tz=tz_naive_fixture)
34+
result = Series(ts)
35+
result.at[1] = ts
36+
expected = Series([ts, ts])
37+
tm.assert_series_equal(result, expected)
38+
39+
3040
class TestAtWithDuplicates:
3141
def test_at_with_duplicate_axes_requires_scalar_lookup(self):
3242
# GH#33041 check that falling back to loc doesn't allow non-scalar

pandas/tests/indexing/test_categorical.py

-19
Original file line numberDiff line numberDiff line change
@@ -430,25 +430,6 @@ def test_ix_categorical_index(self):
430430
)
431431
tm.assert_frame_equal(cdf.loc[:, ["X", "Y"]], expect)
432432

433-
def test_read_only_source(self):
434-
# GH 10043
435-
rw_array = np.eye(10)
436-
rw_df = DataFrame(rw_array)
437-
438-
ro_array = np.eye(10)
439-
ro_array.setflags(write=False)
440-
ro_df = DataFrame(ro_array)
441-
442-
tm.assert_frame_equal(rw_df.iloc[[1, 2, 3]], ro_df.iloc[[1, 2, 3]])
443-
tm.assert_frame_equal(rw_df.iloc[[1]], ro_df.iloc[[1]])
444-
tm.assert_series_equal(rw_df.iloc[1], ro_df.iloc[1])
445-
tm.assert_frame_equal(rw_df.iloc[1:3], ro_df.iloc[1:3])
446-
447-
tm.assert_frame_equal(rw_df.loc[[1, 2, 3]], ro_df.loc[[1, 2, 3]])
448-
tm.assert_frame_equal(rw_df.loc[[1]], ro_df.loc[[1]])
449-
tm.assert_series_equal(rw_df.loc[1], ro_df.loc[1])
450-
tm.assert_frame_equal(rw_df.loc[1:3], ro_df.loc[1:3])
451-
452433
def test_loc_slice(self):
453434
# GH9748
454435
with pytest.raises(KeyError, match="1"):

pandas/tests/indexing/test_datetime.py

+15-32
Original file line numberDiff line numberDiff line change
@@ -160,24 +160,33 @@ def test_indexing_with_datetimeindex_tz(self):
160160
expected = Series([0, 5], index=index)
161161
tm.assert_series_equal(result, expected)
162162

163-
def test_series_partial_set_datetime(self):
163+
@pytest.mark.parametrize("to_period", [True, False])
164+
def test_loc_getitem_listlike_of_datetimelike_keys(self, to_period):
164165
# GH 11497
165166

166167
idx = date_range("2011-01-01", "2011-01-02", freq="D", name="idx")
168+
if to_period:
169+
idx = idx.to_period("D")
167170
ser = Series([0.1, 0.2], index=idx, name="s")
168171

169-
result = ser.loc[[Timestamp("2011-01-01"), Timestamp("2011-01-02")]]
172+
keys = [Timestamp("2011-01-01"), Timestamp("2011-01-02")]
173+
if to_period:
174+
keys = [x.to_period("D") for x in keys]
175+
result = ser.loc[keys]
170176
exp = Series([0.1, 0.2], index=idx, name="s")
171-
exp.index = exp.index._with_freq(None)
177+
if not to_period:
178+
exp.index = exp.index._with_freq(None)
172179
tm.assert_series_equal(result, exp, check_index_type=True)
173180

174181
keys = [
175182
Timestamp("2011-01-02"),
176183
Timestamp("2011-01-02"),
177184
Timestamp("2011-01-01"),
178185
]
186+
if to_period:
187+
keys = [x.to_period("D") for x in keys]
179188
exp = Series(
180-
[0.2, 0.2, 0.1], index=pd.DatetimeIndex(keys, name="idx"), name="s"
189+
[0.2, 0.2, 0.1], index=Index(keys, name="idx", dtype=idx.dtype), name="s"
181190
)
182191
result = ser.loc[keys]
183192
tm.assert_series_equal(result, exp, check_index_type=True)
@@ -187,35 +196,9 @@ def test_series_partial_set_datetime(self):
187196
Timestamp("2011-01-02"),
188197
Timestamp("2011-01-03"),
189198
]
190-
with pytest.raises(KeyError, match="with any missing labels"):
191-
ser.loc[keys]
192-
193-
def test_series_partial_set_period(self):
194-
# GH 11497
195-
196-
idx = pd.period_range("2011-01-01", "2011-01-02", freq="D", name="idx")
197-
ser = Series([0.1, 0.2], index=idx, name="s")
198-
199-
result = ser.loc[
200-
[pd.Period("2011-01-01", freq="D"), pd.Period("2011-01-02", freq="D")]
201-
]
202-
exp = Series([0.1, 0.2], index=idx, name="s")
203-
tm.assert_series_equal(result, exp, check_index_type=True)
199+
if to_period:
200+
keys = [x.to_period("D") for x in keys]
204201

205-
keys = [
206-
pd.Period("2011-01-02", freq="D"),
207-
pd.Period("2011-01-02", freq="D"),
208-
pd.Period("2011-01-01", freq="D"),
209-
]
210-
exp = Series([0.2, 0.2, 0.1], index=pd.PeriodIndex(keys, name="idx"), name="s")
211-
result = ser.loc[keys]
212-
tm.assert_series_equal(result, exp, check_index_type=True)
213-
214-
keys = [
215-
pd.Period("2011-01-03", freq="D"),
216-
pd.Period("2011-01-02", freq="D"),
217-
pd.Period("2011-01-03", freq="D"),
218-
]
219202
with pytest.raises(KeyError, match="with any missing labels"):
220203
ser.loc[keys]
221204

pandas/tests/indexing/test_floats.py

+27-22
Original file line numberDiff line numberDiff line change
@@ -140,8 +140,11 @@ def test_scalar_with_mixed(self):
140140
expected = 3
141141
assert result == expected
142142

143+
@pytest.mark.parametrize(
144+
"idxr,getitem", [(lambda x: x.loc, False), (lambda x: x, True)]
145+
)
143146
@pytest.mark.parametrize("index_func", [tm.makeIntIndex, tm.makeRangeIndex])
144-
def test_scalar_integer(self, index_func, frame_or_series):
147+
def test_scalar_integer(self, index_func, frame_or_series, idxr, getitem):
145148

146149
# test how scalar float indexers work on int indexes
147150

@@ -150,37 +153,39 @@ def test_scalar_integer(self, index_func, frame_or_series):
150153
obj = gen_obj(frame_or_series, i)
151154

152155
# coerce to equal int
153-
for idxr, getitem in [(lambda x: x.loc, False), (lambda x: x, True)]:
154156

155-
result = idxr(obj)[3.0]
156-
self.check(result, obj, 3, getitem)
157+
result = idxr(obj)[3.0]
158+
self.check(result, obj, 3, getitem)
157159

158-
# coerce to equal int
159-
for idxr, getitem in [(lambda x: x.loc, False), (lambda x: x, True)]:
160-
161-
if isinstance(obj, Series):
160+
if isinstance(obj, Series):
162161

163-
def compare(x, y):
164-
assert x == y
162+
def compare(x, y):
163+
assert x == y
165164

166-
expected = 100
165+
expected = 100
166+
else:
167+
compare = tm.assert_series_equal
168+
if getitem:
169+
expected = Series(100, index=range(len(obj)), name=3)
167170
else:
168-
compare = tm.assert_series_equal
169-
if getitem:
170-
expected = Series(100, index=range(len(obj)), name=3)
171-
else:
172-
expected = Series(100.0, index=range(len(obj)), name=3)
171+
expected = Series(100.0, index=range(len(obj)), name=3)
173172

174-
s2 = obj.copy()
175-
idxr(s2)[3.0] = 100
173+
s2 = obj.copy()
174+
idxr(s2)[3.0] = 100
176175

177-
result = idxr(s2)[3.0]
178-
compare(result, expected)
176+
result = idxr(s2)[3.0]
177+
compare(result, expected)
179178

180-
result = idxr(s2)[3]
181-
compare(result, expected)
179+
result = idxr(s2)[3]
180+
compare(result, expected)
182181

182+
@pytest.mark.parametrize("index_func", [tm.makeIntIndex, tm.makeRangeIndex])
183+
def test_scalar_integer_contains_float(self, index_func, frame_or_series):
183184
# contains
185+
# integer index
186+
index = index_func(5)
187+
obj = gen_obj(frame_or_series, index)
188+
184189
# coerce to equal int
185190
assert 3.0 in obj
186191

pandas/tests/indexing/test_iat.py

+13-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
import pandas as pd
1+
import numpy as np
2+
3+
from pandas import DataFrame, Series, period_range
24

35

46
def test_iat(float_frame):
@@ -12,5 +14,14 @@ def test_iat(float_frame):
1214

1315
def test_iat_duplicate_columns():
1416
# https://github.com/pandas-dev/pandas/issues/11754
15-
df = pd.DataFrame([[1, 2]], columns=["x", "x"])
17+
df = DataFrame([[1, 2]], columns=["x", "x"])
1618
assert df.iat[0, 0] == 1
19+
20+
21+
def test_iat_getitem_series_with_period_index():
22+
# GH#4390, iat incorrectly indexing
23+
index = period_range("1/1/2001", periods=10)
24+
ser = Series(np.random.randn(10), index=index)
25+
expected = ser[index[0]]
26+
result = ser.iat[0]
27+
assert expected == result

pandas/tests/indexing/test_iloc.py

+30
Original file line numberDiff line numberDiff line change
@@ -801,6 +801,36 @@ def test_iloc_setitem_empty_frame_raises_with_3d_ndarray(self):
801801
with pytest.raises(ValueError, match=msg):
802802
obj.iloc[nd3] = 0
803803

804+
@pytest.mark.parametrize("indexer", [lambda x: x.loc, lambda x: x.iloc])
805+
def test_iloc_getitem_read_only_values(self, indexer):
806+
# GH#10043 this is fundamentally a test for iloc, but test loc while
807+
# we're here
808+
rw_array = np.eye(10)
809+
rw_df = DataFrame(rw_array)
810+
811+
ro_array = np.eye(10)
812+
ro_array.setflags(write=False)
813+
ro_df = DataFrame(ro_array)
814+
815+
tm.assert_frame_equal(indexer(rw_df)[[1, 2, 3]], indexer(ro_df)[[1, 2, 3]])
816+
tm.assert_frame_equal(indexer(rw_df)[[1]], indexer(ro_df)[[1]])
817+
tm.assert_series_equal(indexer(rw_df)[1], indexer(ro_df)[1])
818+
tm.assert_frame_equal(indexer(rw_df)[1:3], indexer(ro_df)[1:3])
819+
820+
def test_iloc_getitem_readonly_key(self):
821+
# GH#17192 iloc with read-only array raising TypeError
822+
df = DataFrame({"data": np.ones(100, dtype="float64")})
823+
indices = np.array([1, 3, 6])
824+
indices.flags.writeable = False
825+
826+
result = df.iloc[indices]
827+
expected = df.loc[[1, 3, 6]]
828+
tm.assert_frame_equal(result, expected)
829+
830+
result = df["data"].iloc[indices]
831+
expected = df["data"].loc[[1, 3, 6]]
832+
tm.assert_series_equal(result, expected)
833+
804834
def test_iloc_assign_series_to_df_cell(self):
805835
# GH 37593
806836
df = DataFrame(columns=["a"], index=[0])

0 commit comments

Comments
 (0)