Skip to content

Commit 8a752af

Browse files
authored
TST/REF: method-specific files for lookup, get_value, set_value (#37325)
1 parent ef5ccfd commit 8a752af

File tree

6 files changed

+172
-146
lines changed

6 files changed

+172
-146
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import pytest
2+
3+
from pandas import DataFrame, MultiIndex
4+
5+
6+
class TestGetValue:
7+
def test_get_set_value_no_partial_indexing(self):
8+
# partial w/ MultiIndex raise exception
9+
index = MultiIndex.from_tuples([(0, 1), (0, 2), (1, 1), (1, 2)])
10+
df = DataFrame(index=index, columns=range(4))
11+
with pytest.raises(KeyError, match=r"^0$"):
12+
df._get_value(0, 1)
13+
14+
def test_get_value(self, float_frame):
15+
for idx in float_frame.index:
16+
for col in float_frame.columns:
17+
result = float_frame._get_value(idx, col)
18+
expected = float_frame[col][idx]
19+
assert result == expected

pandas/tests/frame/indexing/test_indexing.py

+1-131
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
from pandas._libs import iNaT
88

9-
from pandas.core.dtypes.common import is_float_dtype, is_integer
9+
from pandas.core.dtypes.common import is_integer
1010

1111
import pandas as pd
1212
from pandas import (
@@ -1327,120 +1327,6 @@ def test_getitem_list_duplicates(self):
13271327
expected = df.iloc[:, 2:]
13281328
tm.assert_frame_equal(result, expected)
13291329

1330-
def test_get_value(self, float_frame):
1331-
for idx in float_frame.index:
1332-
for col in float_frame.columns:
1333-
result = float_frame._get_value(idx, col)
1334-
expected = float_frame[col][idx]
1335-
assert result == expected
1336-
1337-
def test_lookup_float(self, float_frame):
1338-
df = float_frame
1339-
rows = list(df.index) * len(df.columns)
1340-
cols = list(df.columns) * len(df.index)
1341-
with tm.assert_produces_warning(FutureWarning):
1342-
result = df.lookup(rows, cols)
1343-
1344-
expected = np.array([df.loc[r, c] for r, c in zip(rows, cols)])
1345-
tm.assert_numpy_array_equal(result, expected)
1346-
1347-
def test_lookup_mixed(self, float_string_frame):
1348-
df = float_string_frame
1349-
rows = list(df.index) * len(df.columns)
1350-
cols = list(df.columns) * len(df.index)
1351-
with tm.assert_produces_warning(FutureWarning):
1352-
result = df.lookup(rows, cols)
1353-
1354-
expected = np.array(
1355-
[df.loc[r, c] for r, c in zip(rows, cols)], dtype=np.object_
1356-
)
1357-
tm.assert_almost_equal(result, expected)
1358-
1359-
def test_lookup_bool(self):
1360-
df = DataFrame(
1361-
{
1362-
"label": ["a", "b", "a", "c"],
1363-
"mask_a": [True, True, False, True],
1364-
"mask_b": [True, False, False, False],
1365-
"mask_c": [False, True, False, True],
1366-
}
1367-
)
1368-
with tm.assert_produces_warning(FutureWarning):
1369-
df["mask"] = df.lookup(df.index, "mask_" + df["label"])
1370-
1371-
exp_mask = np.array(
1372-
[df.loc[r, c] for r, c in zip(df.index, "mask_" + df["label"])]
1373-
)
1374-
1375-
tm.assert_series_equal(df["mask"], Series(exp_mask, name="mask"))
1376-
assert df["mask"].dtype == np.bool_
1377-
1378-
def test_lookup_raises(self, float_frame):
1379-
with pytest.raises(KeyError, match="'One or more row labels was not found'"):
1380-
with tm.assert_produces_warning(FutureWarning):
1381-
float_frame.lookup(["xyz"], ["A"])
1382-
1383-
with pytest.raises(KeyError, match="'One or more column labels was not found'"):
1384-
with tm.assert_produces_warning(FutureWarning):
1385-
float_frame.lookup([float_frame.index[0]], ["xyz"])
1386-
1387-
with pytest.raises(ValueError, match="same size"):
1388-
with tm.assert_produces_warning(FutureWarning):
1389-
float_frame.lookup(["a", "b", "c"], ["a"])
1390-
1391-
def test_lookup_requires_unique_axes(self):
1392-
# GH#33041 raise with a helpful error message
1393-
df = DataFrame(np.random.randn(6).reshape(3, 2), columns=["A", "A"])
1394-
1395-
rows = [0, 1]
1396-
cols = ["A", "A"]
1397-
1398-
# homogeneous-dtype case
1399-
with pytest.raises(ValueError, match="requires unique index and columns"):
1400-
with tm.assert_produces_warning(FutureWarning):
1401-
df.lookup(rows, cols)
1402-
with pytest.raises(ValueError, match="requires unique index and columns"):
1403-
with tm.assert_produces_warning(FutureWarning):
1404-
df.T.lookup(cols, rows)
1405-
1406-
# heterogeneous dtype
1407-
df["B"] = 0
1408-
with pytest.raises(ValueError, match="requires unique index and columns"):
1409-
with tm.assert_produces_warning(FutureWarning):
1410-
df.lookup(rows, cols)
1411-
1412-
def test_set_value(self, float_frame):
1413-
for idx in float_frame.index:
1414-
for col in float_frame.columns:
1415-
float_frame._set_value(idx, col, 1)
1416-
assert float_frame[col][idx] == 1
1417-
1418-
def test_set_value_resize(self, float_frame):
1419-
1420-
res = float_frame._set_value("foobar", "B", 0)
1421-
assert res is None
1422-
assert float_frame.index[-1] == "foobar"
1423-
assert float_frame._get_value("foobar", "B") == 0
1424-
1425-
float_frame.loc["foobar", "qux"] = 0
1426-
assert float_frame._get_value("foobar", "qux") == 0
1427-
1428-
res = float_frame.copy()
1429-
res._set_value("foobar", "baz", "sam")
1430-
assert res["baz"].dtype == np.object_
1431-
1432-
res = float_frame.copy()
1433-
res._set_value("foobar", "baz", True)
1434-
assert res["baz"].dtype == np.object_
1435-
1436-
res = float_frame.copy()
1437-
res._set_value("foobar", "baz", 5)
1438-
assert is_float_dtype(res["baz"])
1439-
assert isna(res["baz"].drop(["foobar"])).all()
1440-
msg = "could not convert string to float: 'sam'"
1441-
with pytest.raises(ValueError, match=msg):
1442-
res._set_value("foobar", "baz", "sam")
1443-
14441330
def test_reindex_with_multi_index(self):
14451331
# https://github.com/pandas-dev/pandas/issues/29896
14461332
# tests for reindexing a multi-indexed DataFrame with a new MultiIndex
@@ -1542,13 +1428,6 @@ def test_set_value_with_index_dtype_change(self):
15421428
assert list(df.index) == list(df_orig.index) + ["C"]
15431429
assert list(df.columns) == list(df_orig.columns) + ["D"]
15441430

1545-
def test_get_set_value_no_partial_indexing(self):
1546-
# partial w/ MultiIndex raise exception
1547-
index = MultiIndex.from_tuples([(0, 1), (0, 2), (1, 1), (1, 2)])
1548-
df = DataFrame(index=index, columns=range(4))
1549-
with pytest.raises(KeyError, match=r"^0$"):
1550-
df._get_value(0, 1)
1551-
15521431
# TODO: rename? remove?
15531432
def test_single_element_ix_dont_upcast(self, float_frame):
15541433
float_frame["E"] = 1
@@ -2251,12 +2130,3 @@ def test_object_casting_indexing_wraps_datetimelike():
22512130
assert blk.dtype == "m8[ns]" # we got the right block
22522131
val = blk.iget((0, 0))
22532132
assert isinstance(val, pd.Timedelta)
2254-
2255-
2256-
def test_lookup_deprecated():
2257-
# GH18262
2258-
df = DataFrame(
2259-
{"col": ["A", "A", "B", "B"], "A": [80, 23, np.nan, 22], "B": [80, 55, 76, 67]}
2260-
)
2261-
with tm.assert_produces_warning(FutureWarning):
2262-
df.lookup(df.index, df["col"])
+91
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
import numpy as np
2+
import pytest
3+
4+
from pandas import DataFrame, Series
5+
import pandas._testing as tm
6+
7+
8+
class TestLookup:
9+
def test_lookup_float(self, float_frame):
10+
df = float_frame
11+
rows = list(df.index) * len(df.columns)
12+
cols = list(df.columns) * len(df.index)
13+
with tm.assert_produces_warning(FutureWarning):
14+
result = df.lookup(rows, cols)
15+
16+
expected = np.array([df.loc[r, c] for r, c in zip(rows, cols)])
17+
tm.assert_numpy_array_equal(result, expected)
18+
19+
def test_lookup_mixed(self, float_string_frame):
20+
df = float_string_frame
21+
rows = list(df.index) * len(df.columns)
22+
cols = list(df.columns) * len(df.index)
23+
with tm.assert_produces_warning(FutureWarning):
24+
result = df.lookup(rows, cols)
25+
26+
expected = np.array(
27+
[df.loc[r, c] for r, c in zip(rows, cols)], dtype=np.object_
28+
)
29+
tm.assert_almost_equal(result, expected)
30+
31+
def test_lookup_bool(self):
32+
df = DataFrame(
33+
{
34+
"label": ["a", "b", "a", "c"],
35+
"mask_a": [True, True, False, True],
36+
"mask_b": [True, False, False, False],
37+
"mask_c": [False, True, False, True],
38+
}
39+
)
40+
with tm.assert_produces_warning(FutureWarning):
41+
df["mask"] = df.lookup(df.index, "mask_" + df["label"])
42+
43+
exp_mask = np.array(
44+
[df.loc[r, c] for r, c in zip(df.index, "mask_" + df["label"])]
45+
)
46+
47+
tm.assert_series_equal(df["mask"], Series(exp_mask, name="mask"))
48+
assert df["mask"].dtype == np.bool_
49+
50+
def test_lookup_raises(self, float_frame):
51+
with pytest.raises(KeyError, match="'One or more row labels was not found'"):
52+
with tm.assert_produces_warning(FutureWarning):
53+
float_frame.lookup(["xyz"], ["A"])
54+
55+
with pytest.raises(KeyError, match="'One or more column labels was not found'"):
56+
with tm.assert_produces_warning(FutureWarning):
57+
float_frame.lookup([float_frame.index[0]], ["xyz"])
58+
59+
with pytest.raises(ValueError, match="same size"):
60+
with tm.assert_produces_warning(FutureWarning):
61+
float_frame.lookup(["a", "b", "c"], ["a"])
62+
63+
def test_lookup_requires_unique_axes(self):
64+
# GH#33041 raise with a helpful error message
65+
df = DataFrame(np.random.randn(6).reshape(3, 2), columns=["A", "A"])
66+
67+
rows = [0, 1]
68+
cols = ["A", "A"]
69+
70+
# homogeneous-dtype case
71+
with pytest.raises(ValueError, match="requires unique index and columns"):
72+
with tm.assert_produces_warning(FutureWarning):
73+
df.lookup(rows, cols)
74+
with pytest.raises(ValueError, match="requires unique index and columns"):
75+
with tm.assert_produces_warning(FutureWarning):
76+
df.T.lookup(cols, rows)
77+
78+
# heterogeneous dtype
79+
df["B"] = 0
80+
with pytest.raises(ValueError, match="requires unique index and columns"):
81+
with tm.assert_produces_warning(FutureWarning):
82+
df.lookup(rows, cols)
83+
84+
85+
def test_lookup_deprecated():
86+
# GH#18262
87+
df = DataFrame(
88+
{"col": ["A", "A", "B", "B"], "A": [80, 23, np.nan, 22], "B": [80, 55, 76, 67]}
89+
)
90+
with tm.assert_produces_warning(FutureWarning):
91+
df.lookup(df.index, df["col"])
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import numpy as np
2+
import pytest
3+
4+
from pandas.core.dtypes.common import is_float_dtype
5+
6+
from pandas import isna
7+
8+
9+
class TestSetValue:
10+
def test_set_value(self, float_frame):
11+
for idx in float_frame.index:
12+
for col in float_frame.columns:
13+
float_frame._set_value(idx, col, 1)
14+
assert float_frame[col][idx] == 1
15+
16+
def test_set_value_resize(self, float_frame):
17+
18+
res = float_frame._set_value("foobar", "B", 0)
19+
assert res is None
20+
assert float_frame.index[-1] == "foobar"
21+
assert float_frame._get_value("foobar", "B") == 0
22+
23+
float_frame.loc["foobar", "qux"] = 0
24+
assert float_frame._get_value("foobar", "qux") == 0
25+
26+
res = float_frame.copy()
27+
res._set_value("foobar", "baz", "sam")
28+
assert res["baz"].dtype == np.object_
29+
30+
res = float_frame.copy()
31+
res._set_value("foobar", "baz", True)
32+
assert res["baz"].dtype == np.object_
33+
34+
res = float_frame.copy()
35+
res._set_value("foobar", "baz", 5)
36+
assert is_float_dtype(res["baz"])
37+
assert isna(res["baz"].drop(["foobar"])).all()
38+
msg = "could not convert string to float: 'sam'"
39+
with pytest.raises(ValueError, match=msg):
40+
res._set_value("foobar", "baz", "sam")

pandas/tests/series/indexing/test_datetime.py

-15
Original file line numberDiff line numberDiff line change
@@ -65,21 +65,6 @@ def test_dti_reset_index_round_trip():
6565
assert df.reset_index()["Date"][0] == stamp
6666

6767

68-
def test_series_set_value():
69-
# #1561
70-
71-
dates = [datetime(2001, 1, 1), datetime(2001, 1, 2)]
72-
index = DatetimeIndex(dates)
73-
74-
s = Series(dtype=object)
75-
s._set_value(dates[0], 1.0)
76-
s._set_value(dates[1], np.nan)
77-
78-
expected = Series([1.0, np.nan], index=index)
79-
80-
tm.assert_series_equal(s, expected)
81-
82-
8368
@pytest.mark.slow
8469
def test_slice_locs_indexerror():
8570
times = [datetime(2000, 1, 1) + timedelta(minutes=i * 10) for i in range(100000)]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from datetime import datetime
2+
3+
import numpy as np
4+
5+
from pandas import DatetimeIndex, Series
6+
import pandas._testing as tm
7+
8+
9+
def test_series_set_value():
10+
# GH#1561
11+
12+
dates = [datetime(2001, 1, 1), datetime(2001, 1, 2)]
13+
index = DatetimeIndex(dates)
14+
15+
s = Series(dtype=object)
16+
s._set_value(dates[0], 1.0)
17+
s._set_value(dates[1], np.nan)
18+
19+
expected = Series([1.0, np.nan], index=index)
20+
21+
tm.assert_series_equal(s, expected)

0 commit comments

Comments
 (0)