Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- ckpts/llama-3b/global_step100/bf16_zero_pp_rank_199_mp_rank_00_optim_states.pt +3 -0
- ckpts/llama-3b/global_step100/bf16_zero_pp_rank_200_mp_rank_02_optim_states.pt +3 -0
- ckpts/llama-3b/global_step100/bf16_zero_pp_rank_210_mp_rank_03_optim_states.pt +3 -0
- ckpts/llama-3b/global_step100/bf16_zero_pp_rank_87_mp_rank_02_optim_states.pt +3 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/__init__.py +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/common.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_check_indexer.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_datetime.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_indexers.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_scalar.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/common.py +40 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/conftest.py +127 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/interval/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/interval/__pycache__/test_interval.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/interval/__pycache__/test_interval_new.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/interval/test_interval_new.py +232 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__init__.py +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_chaining_and_caching.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_datetime.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_getitem.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_iloc.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_indexing_slow.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_loc.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_partial.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_setitem.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_sorted.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_chaining_and_caching.py +87 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_datetime.py +50 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_getitem.py +410 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_iloc.py +171 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_indexing_slow.py +118 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_loc.py +992 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_multiindex.py +235 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_partial.py +269 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_setitem.py +589 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_slice.py +796 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_sorted.py +153 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/test_at.py +257 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/test_categorical.py +573 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/test_chaining_and_caching.py +647 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/test_check_indexer.py +105 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/test_coercion.py +940 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/test_datetime.py +191 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/test_floats.py +689 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/test_iat.py +53 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/test_iloc.py +1478 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/test_indexers.py +61 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexing/test_indexing.py +1157 -0
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_199_mp_rank_00_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9e8f1798072f0f11d0bbc07995ffaed862ee2f6dc490f4bf7e4b9d879873d6f9
|
3 |
+
size 41830148
|
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_200_mp_rank_02_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:7792728dd588180203a3de3a8483f036f23e3fd043befb18df12b2fa51f87bc5
|
3 |
+
size 41830404
|
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_210_mp_rank_03_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:1b128453d9fe939c12054d23d7a8ccfb8b67f75bf12803b8d7deadc4f18009a4
|
3 |
+
size 41830340
|
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_87_mp_rank_02_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:cc377fa51e687aab55530a4e7ef56d9f33ae83f1a60cccf9c57b4cc17e03038a
|
3 |
+
size 41830330
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/__init__.py
ADDED
File without changes
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (189 Bytes). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/common.cpython-310.pyc
ADDED
Binary file (1.29 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_check_indexer.cpython-310.pyc
ADDED
Binary file (2.87 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_datetime.cpython-310.pyc
ADDED
Binary file (5.41 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_indexers.cpython-310.pyc
ADDED
Binary file (2.35 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_scalar.cpython-310.pyc
ADDED
Binary file (9.75 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/common.py
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" common utilities """
|
2 |
+
from __future__ import annotations
|
3 |
+
|
4 |
+
from typing import (
|
5 |
+
Any,
|
6 |
+
Literal,
|
7 |
+
)
|
8 |
+
|
9 |
+
|
10 |
+
def _mklbl(prefix: str, n: int):
|
11 |
+
return [f"{prefix}{i}" for i in range(n)]
|
12 |
+
|
13 |
+
|
14 |
+
def check_indexing_smoketest_or_raises(
|
15 |
+
obj,
|
16 |
+
method: Literal["iloc", "loc"],
|
17 |
+
key: Any,
|
18 |
+
axes: Literal[0, 1] | None = None,
|
19 |
+
fails=None,
|
20 |
+
) -> None:
|
21 |
+
if axes is None:
|
22 |
+
axes_list = [0, 1]
|
23 |
+
else:
|
24 |
+
assert axes in [0, 1]
|
25 |
+
axes_list = [axes]
|
26 |
+
|
27 |
+
for ax in axes_list:
|
28 |
+
if ax < obj.ndim:
|
29 |
+
# create a tuple accessor
|
30 |
+
new_axes = [slice(None)] * obj.ndim
|
31 |
+
new_axes[ax] = key
|
32 |
+
axified = tuple(new_axes)
|
33 |
+
try:
|
34 |
+
getattr(obj, method).__getitem__(axified)
|
35 |
+
except (IndexError, TypeError, KeyError) as detail:
|
36 |
+
# if we are in fails, the ok, otherwise raise it
|
37 |
+
if fails is not None:
|
38 |
+
if isinstance(detail, fails):
|
39 |
+
return
|
40 |
+
raise
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/conftest.py
ADDED
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas import (
|
5 |
+
DataFrame,
|
6 |
+
Index,
|
7 |
+
MultiIndex,
|
8 |
+
Series,
|
9 |
+
date_range,
|
10 |
+
)
|
11 |
+
|
12 |
+
|
13 |
+
@pytest.fixture
|
14 |
+
def series_ints():
|
15 |
+
return Series(np.random.default_rng(2).random(4), index=np.arange(0, 8, 2))
|
16 |
+
|
17 |
+
|
18 |
+
@pytest.fixture
|
19 |
+
def frame_ints():
|
20 |
+
return DataFrame(
|
21 |
+
np.random.default_rng(2).standard_normal((4, 4)),
|
22 |
+
index=np.arange(0, 8, 2),
|
23 |
+
columns=np.arange(0, 12, 3),
|
24 |
+
)
|
25 |
+
|
26 |
+
|
27 |
+
@pytest.fixture
|
28 |
+
def series_uints():
|
29 |
+
return Series(
|
30 |
+
np.random.default_rng(2).random(4),
|
31 |
+
index=Index(np.arange(0, 8, 2, dtype=np.uint64)),
|
32 |
+
)
|
33 |
+
|
34 |
+
|
35 |
+
@pytest.fixture
|
36 |
+
def frame_uints():
|
37 |
+
return DataFrame(
|
38 |
+
np.random.default_rng(2).standard_normal((4, 4)),
|
39 |
+
index=Index(range(0, 8, 2), dtype=np.uint64),
|
40 |
+
columns=Index(range(0, 12, 3), dtype=np.uint64),
|
41 |
+
)
|
42 |
+
|
43 |
+
|
44 |
+
@pytest.fixture
|
45 |
+
def series_labels():
|
46 |
+
return Series(np.random.default_rng(2).standard_normal(4), index=list("abcd"))
|
47 |
+
|
48 |
+
|
49 |
+
@pytest.fixture
|
50 |
+
def frame_labels():
|
51 |
+
return DataFrame(
|
52 |
+
np.random.default_rng(2).standard_normal((4, 4)),
|
53 |
+
index=list("abcd"),
|
54 |
+
columns=list("ABCD"),
|
55 |
+
)
|
56 |
+
|
57 |
+
|
58 |
+
@pytest.fixture
|
59 |
+
def series_ts():
|
60 |
+
return Series(
|
61 |
+
np.random.default_rng(2).standard_normal(4),
|
62 |
+
index=date_range("20130101", periods=4),
|
63 |
+
)
|
64 |
+
|
65 |
+
|
66 |
+
@pytest.fixture
|
67 |
+
def frame_ts():
|
68 |
+
return DataFrame(
|
69 |
+
np.random.default_rng(2).standard_normal((4, 4)),
|
70 |
+
index=date_range("20130101", periods=4),
|
71 |
+
)
|
72 |
+
|
73 |
+
|
74 |
+
@pytest.fixture
|
75 |
+
def series_floats():
|
76 |
+
return Series(
|
77 |
+
np.random.default_rng(2).random(4),
|
78 |
+
index=Index(range(0, 8, 2), dtype=np.float64),
|
79 |
+
)
|
80 |
+
|
81 |
+
|
82 |
+
@pytest.fixture
|
83 |
+
def frame_floats():
|
84 |
+
return DataFrame(
|
85 |
+
np.random.default_rng(2).standard_normal((4, 4)),
|
86 |
+
index=Index(range(0, 8, 2), dtype=np.float64),
|
87 |
+
columns=Index(range(0, 12, 3), dtype=np.float64),
|
88 |
+
)
|
89 |
+
|
90 |
+
|
91 |
+
@pytest.fixture
|
92 |
+
def series_mixed():
|
93 |
+
return Series(np.random.default_rng(2).standard_normal(4), index=[2, 4, "null", 8])
|
94 |
+
|
95 |
+
|
96 |
+
@pytest.fixture
|
97 |
+
def frame_mixed():
|
98 |
+
return DataFrame(
|
99 |
+
np.random.default_rng(2).standard_normal((4, 4)), index=[2, 4, "null", 8]
|
100 |
+
)
|
101 |
+
|
102 |
+
|
103 |
+
@pytest.fixture
|
104 |
+
def frame_empty():
|
105 |
+
return DataFrame()
|
106 |
+
|
107 |
+
|
108 |
+
@pytest.fixture
|
109 |
+
def series_empty():
|
110 |
+
return Series(dtype=object)
|
111 |
+
|
112 |
+
|
113 |
+
@pytest.fixture
|
114 |
+
def frame_multi():
|
115 |
+
return DataFrame(
|
116 |
+
np.random.default_rng(2).standard_normal((4, 4)),
|
117 |
+
index=MultiIndex.from_product([[1, 2], [3, 4]]),
|
118 |
+
columns=MultiIndex.from_product([[5, 6], [7, 8]]),
|
119 |
+
)
|
120 |
+
|
121 |
+
|
122 |
+
@pytest.fixture
|
123 |
+
def series_multi():
|
124 |
+
return Series(
|
125 |
+
np.random.default_rng(2).random(4),
|
126 |
+
index=MultiIndex.from_product([[1, 2], [3, 4]]),
|
127 |
+
)
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/interval/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (198 Bytes). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/interval/__pycache__/test_interval.cpython-310.pyc
ADDED
Binary file (6.89 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/interval/__pycache__/test_interval_new.cpython-310.pyc
ADDED
Binary file (6.75 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/interval/test_interval_new.py
ADDED
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
import pytest
|
5 |
+
|
6 |
+
from pandas.compat import IS64
|
7 |
+
|
8 |
+
from pandas import (
|
9 |
+
Index,
|
10 |
+
Interval,
|
11 |
+
IntervalIndex,
|
12 |
+
Series,
|
13 |
+
)
|
14 |
+
import pandas._testing as tm
|
15 |
+
|
16 |
+
|
17 |
+
class TestIntervalIndex:
|
18 |
+
@pytest.fixture
|
19 |
+
def series_with_interval_index(self):
|
20 |
+
return Series(np.arange(5), IntervalIndex.from_breaks(np.arange(6)))
|
21 |
+
|
22 |
+
def test_loc_with_interval(self, series_with_interval_index, indexer_sl):
|
23 |
+
# loc with single label / list of labels:
|
24 |
+
# - Intervals: only exact matches
|
25 |
+
# - scalars: those that contain it
|
26 |
+
|
27 |
+
ser = series_with_interval_index.copy()
|
28 |
+
|
29 |
+
expected = 0
|
30 |
+
result = indexer_sl(ser)[Interval(0, 1)]
|
31 |
+
assert result == expected
|
32 |
+
|
33 |
+
expected = ser.iloc[3:5]
|
34 |
+
result = indexer_sl(ser)[[Interval(3, 4), Interval(4, 5)]]
|
35 |
+
tm.assert_series_equal(expected, result)
|
36 |
+
|
37 |
+
# missing or not exact
|
38 |
+
with pytest.raises(KeyError, match=re.escape("Interval(3, 5, closed='left')")):
|
39 |
+
indexer_sl(ser)[Interval(3, 5, closed="left")]
|
40 |
+
|
41 |
+
with pytest.raises(KeyError, match=re.escape("Interval(3, 5, closed='right')")):
|
42 |
+
indexer_sl(ser)[Interval(3, 5)]
|
43 |
+
|
44 |
+
with pytest.raises(
|
45 |
+
KeyError, match=re.escape("Interval(-2, 0, closed='right')")
|
46 |
+
):
|
47 |
+
indexer_sl(ser)[Interval(-2, 0)]
|
48 |
+
|
49 |
+
with pytest.raises(KeyError, match=re.escape("Interval(5, 6, closed='right')")):
|
50 |
+
indexer_sl(ser)[Interval(5, 6)]
|
51 |
+
|
52 |
+
def test_loc_with_scalar(self, series_with_interval_index, indexer_sl):
|
53 |
+
# loc with single label / list of labels:
|
54 |
+
# - Intervals: only exact matches
|
55 |
+
# - scalars: those that contain it
|
56 |
+
|
57 |
+
ser = series_with_interval_index.copy()
|
58 |
+
|
59 |
+
assert indexer_sl(ser)[1] == 0
|
60 |
+
assert indexer_sl(ser)[1.5] == 1
|
61 |
+
assert indexer_sl(ser)[2] == 1
|
62 |
+
|
63 |
+
expected = ser.iloc[1:4]
|
64 |
+
tm.assert_series_equal(expected, indexer_sl(ser)[[1.5, 2.5, 3.5]])
|
65 |
+
tm.assert_series_equal(expected, indexer_sl(ser)[[2, 3, 4]])
|
66 |
+
tm.assert_series_equal(expected, indexer_sl(ser)[[1.5, 3, 4]])
|
67 |
+
|
68 |
+
expected = ser.iloc[[1, 1, 2, 1]]
|
69 |
+
tm.assert_series_equal(expected, indexer_sl(ser)[[1.5, 2, 2.5, 1.5]])
|
70 |
+
|
71 |
+
expected = ser.iloc[2:5]
|
72 |
+
tm.assert_series_equal(expected, indexer_sl(ser)[ser >= 2])
|
73 |
+
|
74 |
+
def test_loc_with_slices(self, series_with_interval_index, indexer_sl):
|
75 |
+
# loc with slices:
|
76 |
+
# - Interval objects: only works with exact matches
|
77 |
+
# - scalars: only works for non-overlapping, monotonic intervals,
|
78 |
+
# and start/stop select location based on the interval that
|
79 |
+
# contains them:
|
80 |
+
# (slice_loc(start, stop) == (idx.get_loc(start), idx.get_loc(stop))
|
81 |
+
|
82 |
+
ser = series_with_interval_index.copy()
|
83 |
+
|
84 |
+
# slice of interval
|
85 |
+
|
86 |
+
expected = ser.iloc[:3]
|
87 |
+
result = indexer_sl(ser)[Interval(0, 1) : Interval(2, 3)]
|
88 |
+
tm.assert_series_equal(expected, result)
|
89 |
+
|
90 |
+
expected = ser.iloc[3:]
|
91 |
+
result = indexer_sl(ser)[Interval(3, 4) :]
|
92 |
+
tm.assert_series_equal(expected, result)
|
93 |
+
|
94 |
+
msg = "Interval objects are not currently supported"
|
95 |
+
with pytest.raises(NotImplementedError, match=msg):
|
96 |
+
indexer_sl(ser)[Interval(3, 6) :]
|
97 |
+
|
98 |
+
with pytest.raises(NotImplementedError, match=msg):
|
99 |
+
indexer_sl(ser)[Interval(3, 4, closed="left") :]
|
100 |
+
|
101 |
+
def test_slice_step_ne1(self, series_with_interval_index):
|
102 |
+
# GH#31658 slice of scalar with step != 1
|
103 |
+
ser = series_with_interval_index.copy()
|
104 |
+
expected = ser.iloc[0:4:2]
|
105 |
+
|
106 |
+
result = ser[0:4:2]
|
107 |
+
tm.assert_series_equal(result, expected)
|
108 |
+
|
109 |
+
result2 = ser[0:4][::2]
|
110 |
+
tm.assert_series_equal(result2, expected)
|
111 |
+
|
112 |
+
def test_slice_float_start_stop(self, series_with_interval_index):
|
113 |
+
# GH#31658 slicing with integers is positional, with floats is not
|
114 |
+
# supported
|
115 |
+
ser = series_with_interval_index.copy()
|
116 |
+
|
117 |
+
msg = "label-based slicing with step!=1 is not supported for IntervalIndex"
|
118 |
+
with pytest.raises(ValueError, match=msg):
|
119 |
+
ser[1.5:9.5:2]
|
120 |
+
|
121 |
+
def test_slice_interval_step(self, series_with_interval_index):
|
122 |
+
# GH#31658 allows for integer step!=1, not Interval step
|
123 |
+
ser = series_with_interval_index.copy()
|
124 |
+
msg = "label-based slicing with step!=1 is not supported for IntervalIndex"
|
125 |
+
with pytest.raises(ValueError, match=msg):
|
126 |
+
ser[0 : 4 : Interval(0, 1)]
|
127 |
+
|
128 |
+
def test_loc_with_overlap(self, indexer_sl):
|
129 |
+
idx = IntervalIndex.from_tuples([(1, 5), (3, 7)])
|
130 |
+
ser = Series(range(len(idx)), index=idx)
|
131 |
+
|
132 |
+
# scalar
|
133 |
+
expected = ser
|
134 |
+
result = indexer_sl(ser)[4]
|
135 |
+
tm.assert_series_equal(expected, result)
|
136 |
+
|
137 |
+
result = indexer_sl(ser)[[4]]
|
138 |
+
tm.assert_series_equal(expected, result)
|
139 |
+
|
140 |
+
# interval
|
141 |
+
expected = 0
|
142 |
+
result = indexer_sl(ser)[Interval(1, 5)]
|
143 |
+
assert expected == result
|
144 |
+
|
145 |
+
expected = ser
|
146 |
+
result = indexer_sl(ser)[[Interval(1, 5), Interval(3, 7)]]
|
147 |
+
tm.assert_series_equal(expected, result)
|
148 |
+
|
149 |
+
with pytest.raises(KeyError, match=re.escape("Interval(3, 5, closed='right')")):
|
150 |
+
indexer_sl(ser)[Interval(3, 5)]
|
151 |
+
|
152 |
+
msg = (
|
153 |
+
r"None of \[IntervalIndex\(\[\(3, 5\]\], "
|
154 |
+
r"dtype='interval\[int64, right\]'\)\] are in the \[index\]"
|
155 |
+
)
|
156 |
+
with pytest.raises(KeyError, match=msg):
|
157 |
+
indexer_sl(ser)[[Interval(3, 5)]]
|
158 |
+
|
159 |
+
# slices with interval (only exact matches)
|
160 |
+
expected = ser
|
161 |
+
result = indexer_sl(ser)[Interval(1, 5) : Interval(3, 7)]
|
162 |
+
tm.assert_series_equal(expected, result)
|
163 |
+
|
164 |
+
msg = (
|
165 |
+
"'can only get slices from an IntervalIndex if bounds are "
|
166 |
+
"non-overlapping and all monotonic increasing or decreasing'"
|
167 |
+
)
|
168 |
+
with pytest.raises(KeyError, match=msg):
|
169 |
+
indexer_sl(ser)[Interval(1, 6) : Interval(3, 8)]
|
170 |
+
|
171 |
+
if indexer_sl is tm.loc:
|
172 |
+
# slices with scalar raise for overlapping intervals
|
173 |
+
# TODO KeyError is the appropriate error?
|
174 |
+
with pytest.raises(KeyError, match=msg):
|
175 |
+
ser.loc[1:4]
|
176 |
+
|
177 |
+
def test_non_unique(self, indexer_sl):
|
178 |
+
idx = IntervalIndex.from_tuples([(1, 3), (3, 7)])
|
179 |
+
ser = Series(range(len(idx)), index=idx)
|
180 |
+
|
181 |
+
result = indexer_sl(ser)[Interval(1, 3)]
|
182 |
+
assert result == 0
|
183 |
+
|
184 |
+
result = indexer_sl(ser)[[Interval(1, 3)]]
|
185 |
+
expected = ser.iloc[0:1]
|
186 |
+
tm.assert_series_equal(expected, result)
|
187 |
+
|
188 |
+
def test_non_unique_moar(self, indexer_sl):
|
189 |
+
idx = IntervalIndex.from_tuples([(1, 3), (1, 3), (3, 7)])
|
190 |
+
ser = Series(range(len(idx)), index=idx)
|
191 |
+
|
192 |
+
expected = ser.iloc[[0, 1]]
|
193 |
+
result = indexer_sl(ser)[Interval(1, 3)]
|
194 |
+
tm.assert_series_equal(expected, result)
|
195 |
+
|
196 |
+
expected = ser
|
197 |
+
result = indexer_sl(ser)[Interval(1, 3) :]
|
198 |
+
tm.assert_series_equal(expected, result)
|
199 |
+
|
200 |
+
expected = ser.iloc[[0, 1]]
|
201 |
+
result = indexer_sl(ser)[[Interval(1, 3)]]
|
202 |
+
tm.assert_series_equal(expected, result)
|
203 |
+
|
204 |
+
def test_loc_getitem_missing_key_error_message(
|
205 |
+
self, frame_or_series, series_with_interval_index
|
206 |
+
):
|
207 |
+
# GH#27365
|
208 |
+
ser = series_with_interval_index.copy()
|
209 |
+
obj = frame_or_series(ser)
|
210 |
+
with pytest.raises(KeyError, match=r"\[6\]"):
|
211 |
+
obj.loc[[4, 5, 6]]
|
212 |
+
|
213 |
+
|
214 |
+
@pytest.mark.xfail(not IS64, reason="GH 23440")
|
215 |
+
@pytest.mark.parametrize(
|
216 |
+
"intervals",
|
217 |
+
[
|
218 |
+
([Interval(-np.inf, 0.0), Interval(0.0, 1.0)]),
|
219 |
+
([Interval(-np.inf, -2.0), Interval(-2.0, -1.0)]),
|
220 |
+
([Interval(-1.0, 0.0), Interval(0.0, np.inf)]),
|
221 |
+
([Interval(1.0, 2.0), Interval(2.0, np.inf)]),
|
222 |
+
],
|
223 |
+
)
|
224 |
+
def test_repeating_interval_index_with_infs(intervals):
|
225 |
+
# GH 46658
|
226 |
+
|
227 |
+
interval_index = Index(intervals * 51)
|
228 |
+
|
229 |
+
expected = np.arange(1, 102, 2, dtype=np.intp)
|
230 |
+
result = interval_index.get_indexer_for([intervals[1]])
|
231 |
+
|
232 |
+
tm.assert_equal(result, expected)
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__init__.py
ADDED
File without changes
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (200 Bytes). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_chaining_and_caching.cpython-310.pyc
ADDED
Binary file (2.79 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_datetime.cpython-310.pyc
ADDED
Binary file (1.3 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_getitem.cpython-310.pyc
ADDED
Binary file (11.2 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_iloc.cpython-310.pyc
ADDED
Binary file (5.83 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_indexing_slow.cpython-310.pyc
ADDED
Binary file (3.32 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_loc.cpython-310.pyc
ADDED
Binary file (29.8 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_partial.cpython-310.pyc
ADDED
Binary file (7.05 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_setitem.cpython-310.pyc
ADDED
Binary file (17 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_sorted.cpython-310.pyc
ADDED
Binary file (5.51 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_chaining_and_caching.py
ADDED
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas._libs import index as libindex
|
5 |
+
from pandas.errors import SettingWithCopyError
|
6 |
+
import pandas.util._test_decorators as td
|
7 |
+
|
8 |
+
from pandas import (
|
9 |
+
DataFrame,
|
10 |
+
MultiIndex,
|
11 |
+
Series,
|
12 |
+
)
|
13 |
+
import pandas._testing as tm
|
14 |
+
|
15 |
+
|
16 |
+
def test_detect_chained_assignment(using_copy_on_write, warn_copy_on_write):
|
17 |
+
# Inplace ops, originally from:
|
18 |
+
# https://stackoverflow.com/questions/20508968/series-fillna-in-a-multiindex-dataframe-does-not-fill-is-this-a-bug
|
19 |
+
a = [12, 23]
|
20 |
+
b = [123, None]
|
21 |
+
c = [1234, 2345]
|
22 |
+
d = [12345, 23456]
|
23 |
+
tuples = [("eyes", "left"), ("eyes", "right"), ("ears", "left"), ("ears", "right")]
|
24 |
+
events = {
|
25 |
+
("eyes", "left"): a,
|
26 |
+
("eyes", "right"): b,
|
27 |
+
("ears", "left"): c,
|
28 |
+
("ears", "right"): d,
|
29 |
+
}
|
30 |
+
multiind = MultiIndex.from_tuples(tuples, names=["part", "side"])
|
31 |
+
zed = DataFrame(events, index=["a", "b"], columns=multiind)
|
32 |
+
|
33 |
+
if using_copy_on_write:
|
34 |
+
with tm.raises_chained_assignment_error():
|
35 |
+
zed["eyes"]["right"].fillna(value=555, inplace=True)
|
36 |
+
elif warn_copy_on_write:
|
37 |
+
with tm.assert_produces_warning(None):
|
38 |
+
zed["eyes"]["right"].fillna(value=555, inplace=True)
|
39 |
+
else:
|
40 |
+
msg = "A value is trying to be set on a copy of a slice from a DataFrame"
|
41 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
42 |
+
with tm.assert_produces_warning(None):
|
43 |
+
zed["eyes"]["right"].fillna(value=555, inplace=True)
|
44 |
+
|
45 |
+
|
46 |
+
@td.skip_array_manager_invalid_test # with ArrayManager df.loc[0] is not a view
|
47 |
+
def test_cache_updating(using_copy_on_write, warn_copy_on_write):
|
48 |
+
# 5216
|
49 |
+
# make sure that we don't try to set a dead cache
|
50 |
+
a = np.random.default_rng(2).random((10, 3))
|
51 |
+
df = DataFrame(a, columns=["x", "y", "z"])
|
52 |
+
df_original = df.copy()
|
53 |
+
tuples = [(i, j) for i in range(5) for j in range(2)]
|
54 |
+
index = MultiIndex.from_tuples(tuples)
|
55 |
+
df.index = index
|
56 |
+
|
57 |
+
# setting via chained assignment
|
58 |
+
# but actually works, since everything is a view
|
59 |
+
|
60 |
+
with tm.raises_chained_assignment_error():
|
61 |
+
df.loc[0]["z"].iloc[0] = 1.0
|
62 |
+
|
63 |
+
if using_copy_on_write:
|
64 |
+
assert df.loc[(0, 0), "z"] == df_original.loc[0, "z"]
|
65 |
+
else:
|
66 |
+
result = df.loc[(0, 0), "z"]
|
67 |
+
assert result == 1
|
68 |
+
|
69 |
+
# correct setting
|
70 |
+
df.loc[(0, 0), "z"] = 2
|
71 |
+
result = df.loc[(0, 0), "z"]
|
72 |
+
assert result == 2
|
73 |
+
|
74 |
+
|
75 |
+
def test_indexer_caching(monkeypatch):
|
76 |
+
# GH5727
|
77 |
+
# make sure that indexers are in the _internal_names_set
|
78 |
+
size_cutoff = 20
|
79 |
+
with monkeypatch.context():
|
80 |
+
monkeypatch.setattr(libindex, "_SIZE_CUTOFF", size_cutoff)
|
81 |
+
index = MultiIndex.from_arrays([np.arange(size_cutoff), np.arange(size_cutoff)])
|
82 |
+
s = Series(np.zeros(size_cutoff), index=index)
|
83 |
+
|
84 |
+
# setitem
|
85 |
+
s[s == 0] = 1
|
86 |
+
expected = Series(np.ones(size_cutoff), index=index)
|
87 |
+
tm.assert_series_equal(s, expected)
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_datetime.py
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from datetime import datetime
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
|
5 |
+
from pandas import (
|
6 |
+
DataFrame,
|
7 |
+
Index,
|
8 |
+
MultiIndex,
|
9 |
+
Period,
|
10 |
+
Series,
|
11 |
+
period_range,
|
12 |
+
to_datetime,
|
13 |
+
)
|
14 |
+
import pandas._testing as tm
|
15 |
+
|
16 |
+
|
17 |
+
def test_multiindex_period_datetime():
|
18 |
+
# GH4861, using datetime in period of multiindex raises exception
|
19 |
+
|
20 |
+
idx1 = Index(["a", "a", "a", "b", "b"])
|
21 |
+
idx2 = period_range("2012-01", periods=len(idx1), freq="M")
|
22 |
+
s = Series(np.random.default_rng(2).standard_normal(len(idx1)), [idx1, idx2])
|
23 |
+
|
24 |
+
# try Period as index
|
25 |
+
expected = s.iloc[0]
|
26 |
+
result = s.loc["a", Period("2012-01")]
|
27 |
+
assert result == expected
|
28 |
+
|
29 |
+
# try datetime as index
|
30 |
+
result = s.loc["a", datetime(2012, 1, 1)]
|
31 |
+
assert result == expected
|
32 |
+
|
33 |
+
|
34 |
+
def test_multiindex_datetime_columns():
|
35 |
+
# GH35015, using datetime as column indices raises exception
|
36 |
+
|
37 |
+
mi = MultiIndex.from_tuples(
|
38 |
+
[(to_datetime("02/29/2020"), to_datetime("03/01/2020"))], names=["a", "b"]
|
39 |
+
)
|
40 |
+
|
41 |
+
df = DataFrame([], columns=mi)
|
42 |
+
|
43 |
+
expected_df = DataFrame(
|
44 |
+
[],
|
45 |
+
columns=MultiIndex.from_arrays(
|
46 |
+
[[to_datetime("02/29/2020")], [to_datetime("03/01/2020")]], names=["a", "b"]
|
47 |
+
),
|
48 |
+
)
|
49 |
+
|
50 |
+
tm.assert_frame_equal(df, expected_df)
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_getitem.py
ADDED
@@ -0,0 +1,410 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas import (
|
5 |
+
DataFrame,
|
6 |
+
Index,
|
7 |
+
MultiIndex,
|
8 |
+
Series,
|
9 |
+
)
|
10 |
+
import pandas._testing as tm
|
11 |
+
from pandas.core.indexing import IndexingError
|
12 |
+
|
13 |
+
# ----------------------------------------------------------------------------
|
14 |
+
# test indexing of Series with multi-level Index
|
15 |
+
# ----------------------------------------------------------------------------
|
16 |
+
|
17 |
+
|
18 |
+
@pytest.mark.parametrize(
|
19 |
+
"access_method",
|
20 |
+
[lambda s, x: s[:, x], lambda s, x: s.loc[:, x], lambda s, x: s.xs(x, level=1)],
|
21 |
+
)
|
22 |
+
@pytest.mark.parametrize(
|
23 |
+
"level1_value, expected",
|
24 |
+
[(0, Series([1], index=[0])), (1, Series([2, 3], index=[1, 2]))],
|
25 |
+
)
|
26 |
+
def test_series_getitem_multiindex(access_method, level1_value, expected):
|
27 |
+
# GH 6018
|
28 |
+
# series regression getitem with a multi-index
|
29 |
+
|
30 |
+
mi = MultiIndex.from_tuples([(0, 0), (1, 1), (2, 1)], names=["A", "B"])
|
31 |
+
ser = Series([1, 2, 3], index=mi)
|
32 |
+
expected.index.name = "A"
|
33 |
+
|
34 |
+
result = access_method(ser, level1_value)
|
35 |
+
tm.assert_series_equal(result, expected)
|
36 |
+
|
37 |
+
|
38 |
+
@pytest.mark.parametrize("level0_value", ["D", "A"])
|
39 |
+
def test_series_getitem_duplicates_multiindex(level0_value):
|
40 |
+
# GH 5725 the 'A' happens to be a valid Timestamp so the doesn't raise
|
41 |
+
# the appropriate error, only in PY3 of course!
|
42 |
+
|
43 |
+
index = MultiIndex(
|
44 |
+
levels=[[level0_value, "B", "C"], [0, 26, 27, 37, 57, 67, 75, 82]],
|
45 |
+
codes=[[0, 0, 0, 1, 2, 2, 2, 2, 2, 2], [1, 3, 4, 6, 0, 2, 2, 3, 5, 7]],
|
46 |
+
names=["tag", "day"],
|
47 |
+
)
|
48 |
+
arr = np.random.default_rng(2).standard_normal((len(index), 1))
|
49 |
+
df = DataFrame(arr, index=index, columns=["val"])
|
50 |
+
|
51 |
+
# confirm indexing on missing value raises KeyError
|
52 |
+
if level0_value != "A":
|
53 |
+
with pytest.raises(KeyError, match=r"^'A'$"):
|
54 |
+
df.val["A"]
|
55 |
+
|
56 |
+
with pytest.raises(KeyError, match=r"^'X'$"):
|
57 |
+
df.val["X"]
|
58 |
+
|
59 |
+
result = df.val[level0_value]
|
60 |
+
expected = Series(
|
61 |
+
arr.ravel()[0:3], name="val", index=Index([26, 37, 57], name="day")
|
62 |
+
)
|
63 |
+
tm.assert_series_equal(result, expected)
|
64 |
+
|
65 |
+
|
66 |
+
def test_series_getitem(multiindex_year_month_day_dataframe_random_data, indexer_sl):
|
67 |
+
s = multiindex_year_month_day_dataframe_random_data["A"]
|
68 |
+
expected = s.reindex(s.index[42:65])
|
69 |
+
expected.index = expected.index.droplevel(0).droplevel(0)
|
70 |
+
|
71 |
+
result = indexer_sl(s)[2000, 3]
|
72 |
+
tm.assert_series_equal(result, expected)
|
73 |
+
|
74 |
+
|
75 |
+
def test_series_getitem_returns_scalar(
|
76 |
+
multiindex_year_month_day_dataframe_random_data, indexer_sl
|
77 |
+
):
|
78 |
+
s = multiindex_year_month_day_dataframe_random_data["A"]
|
79 |
+
expected = s.iloc[49]
|
80 |
+
|
81 |
+
result = indexer_sl(s)[2000, 3, 10]
|
82 |
+
assert result == expected
|
83 |
+
|
84 |
+
|
85 |
+
@pytest.mark.parametrize(
|
86 |
+
"indexer,expected_error,expected_error_msg",
|
87 |
+
[
|
88 |
+
(lambda s: s.__getitem__((2000, 3, 4)), KeyError, r"^\(2000, 3, 4\)$"),
|
89 |
+
(lambda s: s[(2000, 3, 4)], KeyError, r"^\(2000, 3, 4\)$"),
|
90 |
+
(lambda s: s.loc[(2000, 3, 4)], KeyError, r"^\(2000, 3, 4\)$"),
|
91 |
+
(lambda s: s.loc[(2000, 3, 4, 5)], IndexingError, "Too many indexers"),
|
92 |
+
(lambda s: s.__getitem__(len(s)), KeyError, ""), # match should include len(s)
|
93 |
+
(lambda s: s[len(s)], KeyError, ""), # match should include len(s)
|
94 |
+
(
|
95 |
+
lambda s: s.iloc[len(s)],
|
96 |
+
IndexError,
|
97 |
+
"single positional indexer is out-of-bounds",
|
98 |
+
),
|
99 |
+
],
|
100 |
+
)
|
101 |
+
def test_series_getitem_indexing_errors(
|
102 |
+
multiindex_year_month_day_dataframe_random_data,
|
103 |
+
indexer,
|
104 |
+
expected_error,
|
105 |
+
expected_error_msg,
|
106 |
+
):
|
107 |
+
s = multiindex_year_month_day_dataframe_random_data["A"]
|
108 |
+
with pytest.raises(expected_error, match=expected_error_msg):
|
109 |
+
indexer(s)
|
110 |
+
|
111 |
+
|
112 |
+
def test_series_getitem_corner_generator(
|
113 |
+
multiindex_year_month_day_dataframe_random_data,
|
114 |
+
):
|
115 |
+
s = multiindex_year_month_day_dataframe_random_data["A"]
|
116 |
+
result = s[(x > 0 for x in s)]
|
117 |
+
expected = s[s > 0]
|
118 |
+
tm.assert_series_equal(result, expected)
|
119 |
+
|
120 |
+
|
121 |
+
# ----------------------------------------------------------------------------
|
122 |
+
# test indexing of DataFrame with multi-level Index
|
123 |
+
# ----------------------------------------------------------------------------
|
124 |
+
|
125 |
+
|
126 |
+
def test_getitem_simple(multiindex_dataframe_random_data):
|
127 |
+
df = multiindex_dataframe_random_data.T
|
128 |
+
expected = df.values[:, 0]
|
129 |
+
result = df["foo", "one"].values
|
130 |
+
tm.assert_almost_equal(result, expected)
|
131 |
+
|
132 |
+
|
133 |
+
@pytest.mark.parametrize(
|
134 |
+
"indexer,expected_error_msg",
|
135 |
+
[
|
136 |
+
(lambda df: df[("foo", "four")], r"^\('foo', 'four'\)$"),
|
137 |
+
(lambda df: df["foobar"], r"^'foobar'$"),
|
138 |
+
],
|
139 |
+
)
|
140 |
+
def test_frame_getitem_simple_key_error(
|
141 |
+
multiindex_dataframe_random_data, indexer, expected_error_msg
|
142 |
+
):
|
143 |
+
df = multiindex_dataframe_random_data.T
|
144 |
+
with pytest.raises(KeyError, match=expected_error_msg):
|
145 |
+
indexer(df)
|
146 |
+
|
147 |
+
|
148 |
+
def test_tuple_string_column_names():
|
149 |
+
# GH#50372
|
150 |
+
mi = MultiIndex.from_tuples([("a", "aa"), ("a", "ab"), ("b", "ba"), ("b", "bb")])
|
151 |
+
df = DataFrame([range(4), range(1, 5), range(2, 6)], columns=mi)
|
152 |
+
df["single_index"] = 0
|
153 |
+
|
154 |
+
df_flat = df.copy()
|
155 |
+
df_flat.columns = df_flat.columns.to_flat_index()
|
156 |
+
df_flat["new_single_index"] = 0
|
157 |
+
|
158 |
+
result = df_flat[[("a", "aa"), "new_single_index"]]
|
159 |
+
expected = DataFrame(
|
160 |
+
[[0, 0], [1, 0], [2, 0]], columns=Index([("a", "aa"), "new_single_index"])
|
161 |
+
)
|
162 |
+
tm.assert_frame_equal(result, expected)
|
163 |
+
|
164 |
+
|
165 |
+
def test_frame_getitem_multicolumn_empty_level():
|
166 |
+
df = DataFrame({"a": ["1", "2", "3"], "b": ["2", "3", "4"]})
|
167 |
+
df.columns = [
|
168 |
+
["level1 item1", "level1 item2"],
|
169 |
+
["", "level2 item2"],
|
170 |
+
["level3 item1", "level3 item2"],
|
171 |
+
]
|
172 |
+
|
173 |
+
result = df["level1 item1"]
|
174 |
+
expected = DataFrame(
|
175 |
+
[["1"], ["2"], ["3"]], index=df.index, columns=["level3 item1"]
|
176 |
+
)
|
177 |
+
tm.assert_frame_equal(result, expected)
|
178 |
+
|
179 |
+
|
180 |
+
@pytest.mark.parametrize(
|
181 |
+
"indexer,expected_slice",
|
182 |
+
[
|
183 |
+
(lambda df: df["foo"], slice(3)),
|
184 |
+
(lambda df: df["bar"], slice(3, 5)),
|
185 |
+
(lambda df: df.loc[:, "bar"], slice(3, 5)),
|
186 |
+
],
|
187 |
+
)
|
188 |
+
def test_frame_getitem_toplevel(
|
189 |
+
multiindex_dataframe_random_data, indexer, expected_slice
|
190 |
+
):
|
191 |
+
df = multiindex_dataframe_random_data.T
|
192 |
+
expected = df.reindex(columns=df.columns[expected_slice])
|
193 |
+
expected.columns = expected.columns.droplevel(0)
|
194 |
+
result = indexer(df)
|
195 |
+
tm.assert_frame_equal(result, expected)
|
196 |
+
|
197 |
+
|
198 |
+
def test_frame_mixed_depth_get():
|
199 |
+
arrays = [
|
200 |
+
["a", "top", "top", "routine1", "routine1", "routine2"],
|
201 |
+
["", "OD", "OD", "result1", "result2", "result1"],
|
202 |
+
["", "wx", "wy", "", "", ""],
|
203 |
+
]
|
204 |
+
|
205 |
+
tuples = sorted(zip(*arrays))
|
206 |
+
index = MultiIndex.from_tuples(tuples)
|
207 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((4, 6)), columns=index)
|
208 |
+
|
209 |
+
result = df["a"]
|
210 |
+
expected = df["a", "", ""].rename("a")
|
211 |
+
tm.assert_series_equal(result, expected)
|
212 |
+
|
213 |
+
result = df["routine1", "result1"]
|
214 |
+
expected = df["routine1", "result1", ""]
|
215 |
+
expected = expected.rename(("routine1", "result1"))
|
216 |
+
tm.assert_series_equal(result, expected)
|
217 |
+
|
218 |
+
|
219 |
+
def test_frame_getitem_nan_multiindex(nulls_fixture):
|
220 |
+
# GH#29751
|
221 |
+
# loc on a multiindex containing nan values
|
222 |
+
n = nulls_fixture # for code readability
|
223 |
+
cols = ["a", "b", "c"]
|
224 |
+
df = DataFrame(
|
225 |
+
[[11, n, 13], [21, n, 23], [31, n, 33], [41, n, 43]],
|
226 |
+
columns=cols,
|
227 |
+
).set_index(["a", "b"])
|
228 |
+
df["c"] = df["c"].astype("int64")
|
229 |
+
|
230 |
+
idx = (21, n)
|
231 |
+
result = df.loc[:idx]
|
232 |
+
expected = DataFrame([[11, n, 13], [21, n, 23]], columns=cols).set_index(["a", "b"])
|
233 |
+
expected["c"] = expected["c"].astype("int64")
|
234 |
+
tm.assert_frame_equal(result, expected)
|
235 |
+
|
236 |
+
result = df.loc[idx:]
|
237 |
+
expected = DataFrame(
|
238 |
+
[[21, n, 23], [31, n, 33], [41, n, 43]], columns=cols
|
239 |
+
).set_index(["a", "b"])
|
240 |
+
expected["c"] = expected["c"].astype("int64")
|
241 |
+
tm.assert_frame_equal(result, expected)
|
242 |
+
|
243 |
+
idx1, idx2 = (21, n), (31, n)
|
244 |
+
result = df.loc[idx1:idx2]
|
245 |
+
expected = DataFrame([[21, n, 23], [31, n, 33]], columns=cols).set_index(["a", "b"])
|
246 |
+
expected["c"] = expected["c"].astype("int64")
|
247 |
+
tm.assert_frame_equal(result, expected)
|
248 |
+
|
249 |
+
|
250 |
+
@pytest.mark.parametrize(
|
251 |
+
"indexer,expected",
|
252 |
+
[
|
253 |
+
(
|
254 |
+
(["b"], ["bar", np.nan]),
|
255 |
+
(
|
256 |
+
DataFrame(
|
257 |
+
[[2, 3], [5, 6]],
|
258 |
+
columns=MultiIndex.from_tuples([("b", "bar"), ("b", np.nan)]),
|
259 |
+
dtype="int64",
|
260 |
+
)
|
261 |
+
),
|
262 |
+
),
|
263 |
+
(
|
264 |
+
(["a", "b"]),
|
265 |
+
(
|
266 |
+
DataFrame(
|
267 |
+
[[1, 2, 3], [4, 5, 6]],
|
268 |
+
columns=MultiIndex.from_tuples(
|
269 |
+
[("a", "foo"), ("b", "bar"), ("b", np.nan)]
|
270 |
+
),
|
271 |
+
dtype="int64",
|
272 |
+
)
|
273 |
+
),
|
274 |
+
),
|
275 |
+
(
|
276 |
+
(["b"]),
|
277 |
+
(
|
278 |
+
DataFrame(
|
279 |
+
[[2, 3], [5, 6]],
|
280 |
+
columns=MultiIndex.from_tuples([("b", "bar"), ("b", np.nan)]),
|
281 |
+
dtype="int64",
|
282 |
+
)
|
283 |
+
),
|
284 |
+
),
|
285 |
+
(
|
286 |
+
(["b"], ["bar"]),
|
287 |
+
(
|
288 |
+
DataFrame(
|
289 |
+
[[2], [5]],
|
290 |
+
columns=MultiIndex.from_tuples([("b", "bar")]),
|
291 |
+
dtype="int64",
|
292 |
+
)
|
293 |
+
),
|
294 |
+
),
|
295 |
+
(
|
296 |
+
(["b"], [np.nan]),
|
297 |
+
(
|
298 |
+
DataFrame(
|
299 |
+
[[3], [6]],
|
300 |
+
columns=MultiIndex(
|
301 |
+
codes=[[1], [-1]], levels=[["a", "b"], ["bar", "foo"]]
|
302 |
+
),
|
303 |
+
dtype="int64",
|
304 |
+
)
|
305 |
+
),
|
306 |
+
),
|
307 |
+
(("b", np.nan), Series([3, 6], dtype="int64", name=("b", np.nan))),
|
308 |
+
],
|
309 |
+
)
|
310 |
+
def test_frame_getitem_nan_cols_multiindex(
|
311 |
+
indexer,
|
312 |
+
expected,
|
313 |
+
nulls_fixture,
|
314 |
+
):
|
315 |
+
# Slicing MultiIndex including levels with nan values, for more information
|
316 |
+
# see GH#25154
|
317 |
+
df = DataFrame(
|
318 |
+
[[1, 2, 3], [4, 5, 6]],
|
319 |
+
columns=MultiIndex.from_tuples(
|
320 |
+
[("a", "foo"), ("b", "bar"), ("b", nulls_fixture)]
|
321 |
+
),
|
322 |
+
dtype="int64",
|
323 |
+
)
|
324 |
+
|
325 |
+
result = df.loc[:, indexer]
|
326 |
+
tm.assert_equal(result, expected)
|
327 |
+
|
328 |
+
|
329 |
+
# ----------------------------------------------------------------------------
|
330 |
+
# test indexing of DataFrame with multi-level Index with duplicates
|
331 |
+
# ----------------------------------------------------------------------------
|
332 |
+
|
333 |
+
|
334 |
+
@pytest.fixture
|
335 |
+
def dataframe_with_duplicate_index():
|
336 |
+
"""Fixture for DataFrame used in tests for gh-4145 and gh-4146"""
|
337 |
+
data = [["a", "d", "e", "c", "f", "b"], [1, 4, 5, 3, 6, 2], [1, 4, 5, 3, 6, 2]]
|
338 |
+
index = ["h1", "h3", "h5"]
|
339 |
+
columns = MultiIndex(
|
340 |
+
levels=[["A", "B"], ["A1", "A2", "B1", "B2"]],
|
341 |
+
codes=[[0, 0, 0, 1, 1, 1], [0, 3, 3, 0, 1, 2]],
|
342 |
+
names=["main", "sub"],
|
343 |
+
)
|
344 |
+
return DataFrame(data, index=index, columns=columns)
|
345 |
+
|
346 |
+
|
347 |
+
@pytest.mark.parametrize(
|
348 |
+
"indexer", [lambda df: df[("A", "A1")], lambda df: df.loc[:, ("A", "A1")]]
|
349 |
+
)
|
350 |
+
def test_frame_mi_access(dataframe_with_duplicate_index, indexer):
|
351 |
+
# GH 4145
|
352 |
+
df = dataframe_with_duplicate_index
|
353 |
+
index = Index(["h1", "h3", "h5"])
|
354 |
+
columns = MultiIndex.from_tuples([("A", "A1")], names=["main", "sub"])
|
355 |
+
expected = DataFrame([["a", 1, 1]], index=columns, columns=index).T
|
356 |
+
|
357 |
+
result = indexer(df)
|
358 |
+
tm.assert_frame_equal(result, expected)
|
359 |
+
|
360 |
+
|
361 |
+
def test_frame_mi_access_returns_series(dataframe_with_duplicate_index):
|
362 |
+
# GH 4146, not returning a block manager when selecting a unique index
|
363 |
+
# from a duplicate index
|
364 |
+
# as of 4879, this returns a Series (which is similar to what happens
|
365 |
+
# with a non-unique)
|
366 |
+
df = dataframe_with_duplicate_index
|
367 |
+
expected = Series(["a", 1, 1], index=["h1", "h3", "h5"], name="A1")
|
368 |
+
result = df["A"]["A1"]
|
369 |
+
tm.assert_series_equal(result, expected)
|
370 |
+
|
371 |
+
|
372 |
+
def test_frame_mi_access_returns_frame(dataframe_with_duplicate_index):
|
373 |
+
# selecting a non_unique from the 2nd level
|
374 |
+
df = dataframe_with_duplicate_index
|
375 |
+
expected = DataFrame(
|
376 |
+
[["d", 4, 4], ["e", 5, 5]],
|
377 |
+
index=Index(["B2", "B2"], name="sub"),
|
378 |
+
columns=["h1", "h3", "h5"],
|
379 |
+
).T
|
380 |
+
result = df["A"]["B2"]
|
381 |
+
tm.assert_frame_equal(result, expected)
|
382 |
+
|
383 |
+
|
384 |
+
def test_frame_mi_empty_slice():
|
385 |
+
# GH 15454
|
386 |
+
df = DataFrame(0, index=range(2), columns=MultiIndex.from_product([[1], [2]]))
|
387 |
+
result = df[[]]
|
388 |
+
expected = DataFrame(
|
389 |
+
index=[0, 1], columns=MultiIndex(levels=[[1], [2]], codes=[[], []])
|
390 |
+
)
|
391 |
+
tm.assert_frame_equal(result, expected)
|
392 |
+
|
393 |
+
|
394 |
+
def test_loc_empty_multiindex():
|
395 |
+
# GH#36936
|
396 |
+
arrays = [["a", "a", "b", "a"], ["a", "a", "b", "b"]]
|
397 |
+
index = MultiIndex.from_arrays(arrays, names=("idx1", "idx2"))
|
398 |
+
df = DataFrame([1, 2, 3, 4], index=index, columns=["value"])
|
399 |
+
|
400 |
+
# loc on empty multiindex == loc with False mask
|
401 |
+
empty_multiindex = df.loc[df.loc[:, "value"] == 0, :].index
|
402 |
+
result = df.loc[empty_multiindex, :]
|
403 |
+
expected = df.loc[[False] * len(df.index), :]
|
404 |
+
tm.assert_frame_equal(result, expected)
|
405 |
+
|
406 |
+
# replacing value with loc on empty multiindex
|
407 |
+
df.loc[df.loc[df.loc[:, "value"] == 0].index, "value"] = 5
|
408 |
+
result = df
|
409 |
+
expected = DataFrame([1, 2, 3, 4], index=index, columns=["value"])
|
410 |
+
tm.assert_frame_equal(result, expected)
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_iloc.py
ADDED
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas import (
|
5 |
+
DataFrame,
|
6 |
+
MultiIndex,
|
7 |
+
Series,
|
8 |
+
)
|
9 |
+
import pandas._testing as tm
|
10 |
+
|
11 |
+
|
12 |
+
@pytest.fixture
|
13 |
+
def simple_multiindex_dataframe():
|
14 |
+
"""
|
15 |
+
Factory function to create simple 3 x 3 dataframe with
|
16 |
+
both columns and row MultiIndex using supplied data or
|
17 |
+
random data by default.
|
18 |
+
"""
|
19 |
+
|
20 |
+
data = np.random.default_rng(2).standard_normal((3, 3))
|
21 |
+
return DataFrame(
|
22 |
+
data, columns=[[2, 2, 4], [6, 8, 10]], index=[[4, 4, 8], [8, 10, 12]]
|
23 |
+
)
|
24 |
+
|
25 |
+
|
26 |
+
@pytest.mark.parametrize(
|
27 |
+
"indexer, expected",
|
28 |
+
[
|
29 |
+
(
|
30 |
+
lambda df: df.iloc[0],
|
31 |
+
lambda arr: Series(arr[0], index=[[2, 2, 4], [6, 8, 10]], name=(4, 8)),
|
32 |
+
),
|
33 |
+
(
|
34 |
+
lambda df: df.iloc[2],
|
35 |
+
lambda arr: Series(arr[2], index=[[2, 2, 4], [6, 8, 10]], name=(8, 12)),
|
36 |
+
),
|
37 |
+
(
|
38 |
+
lambda df: df.iloc[:, 2],
|
39 |
+
lambda arr: Series(arr[:, 2], index=[[4, 4, 8], [8, 10, 12]], name=(4, 10)),
|
40 |
+
),
|
41 |
+
],
|
42 |
+
)
|
43 |
+
def test_iloc_returns_series(indexer, expected, simple_multiindex_dataframe):
|
44 |
+
df = simple_multiindex_dataframe
|
45 |
+
arr = df.values
|
46 |
+
result = indexer(df)
|
47 |
+
expected = expected(arr)
|
48 |
+
tm.assert_series_equal(result, expected)
|
49 |
+
|
50 |
+
|
51 |
+
def test_iloc_returns_dataframe(simple_multiindex_dataframe):
|
52 |
+
df = simple_multiindex_dataframe
|
53 |
+
result = df.iloc[[0, 1]]
|
54 |
+
expected = df.xs(4, drop_level=False)
|
55 |
+
tm.assert_frame_equal(result, expected)
|
56 |
+
|
57 |
+
|
58 |
+
def test_iloc_returns_scalar(simple_multiindex_dataframe):
|
59 |
+
df = simple_multiindex_dataframe
|
60 |
+
arr = df.values
|
61 |
+
result = df.iloc[2, 2]
|
62 |
+
expected = arr[2, 2]
|
63 |
+
assert result == expected
|
64 |
+
|
65 |
+
|
66 |
+
def test_iloc_getitem_multiple_items():
|
67 |
+
# GH 5528
|
68 |
+
tup = zip(*[["a", "a", "b", "b"], ["x", "y", "x", "y"]])
|
69 |
+
index = MultiIndex.from_tuples(tup)
|
70 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((4, 4)), index=index)
|
71 |
+
result = df.iloc[[2, 3]]
|
72 |
+
expected = df.xs("b", drop_level=False)
|
73 |
+
tm.assert_frame_equal(result, expected)
|
74 |
+
|
75 |
+
|
76 |
+
def test_iloc_getitem_labels():
|
77 |
+
# this is basically regular indexing
|
78 |
+
arr = np.random.default_rng(2).standard_normal((4, 3))
|
79 |
+
df = DataFrame(
|
80 |
+
arr,
|
81 |
+
columns=[["i", "i", "j"], ["A", "A", "B"]],
|
82 |
+
index=[["i", "i", "j", "k"], ["X", "X", "Y", "Y"]],
|
83 |
+
)
|
84 |
+
result = df.iloc[2, 2]
|
85 |
+
expected = arr[2, 2]
|
86 |
+
assert result == expected
|
87 |
+
|
88 |
+
|
89 |
+
def test_frame_getitem_slice(multiindex_dataframe_random_data):
|
90 |
+
df = multiindex_dataframe_random_data
|
91 |
+
result = df.iloc[:4]
|
92 |
+
expected = df[:4]
|
93 |
+
tm.assert_frame_equal(result, expected)
|
94 |
+
|
95 |
+
|
96 |
+
def test_frame_setitem_slice(multiindex_dataframe_random_data):
|
97 |
+
df = multiindex_dataframe_random_data
|
98 |
+
df.iloc[:4] = 0
|
99 |
+
|
100 |
+
assert (df.values[:4] == 0).all()
|
101 |
+
assert (df.values[4:] != 0).all()
|
102 |
+
|
103 |
+
|
104 |
+
def test_indexing_ambiguity_bug_1678():
|
105 |
+
# GH 1678
|
106 |
+
columns = MultiIndex.from_tuples(
|
107 |
+
[("Ohio", "Green"), ("Ohio", "Red"), ("Colorado", "Green")]
|
108 |
+
)
|
109 |
+
index = MultiIndex.from_tuples([("a", 1), ("a", 2), ("b", 1), ("b", 2)])
|
110 |
+
|
111 |
+
df = DataFrame(np.arange(12).reshape((4, 3)), index=index, columns=columns)
|
112 |
+
|
113 |
+
result = df.iloc[:, 1]
|
114 |
+
expected = df.loc[:, ("Ohio", "Red")]
|
115 |
+
tm.assert_series_equal(result, expected)
|
116 |
+
|
117 |
+
|
118 |
+
def test_iloc_integer_locations():
|
119 |
+
# GH 13797
|
120 |
+
data = [
|
121 |
+
["str00", "str01"],
|
122 |
+
["str10", "str11"],
|
123 |
+
["str20", "srt21"],
|
124 |
+
["str30", "str31"],
|
125 |
+
["str40", "str41"],
|
126 |
+
]
|
127 |
+
|
128 |
+
index = MultiIndex.from_tuples(
|
129 |
+
[("CC", "A"), ("CC", "B"), ("CC", "B"), ("BB", "a"), ("BB", "b")]
|
130 |
+
)
|
131 |
+
|
132 |
+
expected = DataFrame(data)
|
133 |
+
df = DataFrame(data, index=index)
|
134 |
+
|
135 |
+
result = DataFrame([[df.iloc[r, c] for c in range(2)] for r in range(5)])
|
136 |
+
|
137 |
+
tm.assert_frame_equal(result, expected)
|
138 |
+
|
139 |
+
|
140 |
+
@pytest.mark.parametrize(
|
141 |
+
"data, indexes, values, expected_k",
|
142 |
+
[
|
143 |
+
# test without indexer value in first level of MultiIndex
|
144 |
+
([[2, 22, 5], [2, 33, 6]], [0, -1, 1], [2, 3, 1], [7, 10]),
|
145 |
+
# test like code sample 1 in the issue
|
146 |
+
([[1, 22, 555], [1, 33, 666]], [0, -1, 1], [200, 300, 100], [755, 1066]),
|
147 |
+
# test like code sample 2 in the issue
|
148 |
+
([[1, 3, 7], [2, 4, 8]], [0, -1, 1], [10, 10, 1000], [17, 1018]),
|
149 |
+
# test like code sample 3 in the issue
|
150 |
+
([[1, 11, 4], [2, 22, 5], [3, 33, 6]], [0, -1, 1], [4, 7, 10], [8, 15, 13]),
|
151 |
+
],
|
152 |
+
)
|
153 |
+
def test_iloc_setitem_int_multiindex_series(data, indexes, values, expected_k):
|
154 |
+
# GH17148
|
155 |
+
df = DataFrame(data=data, columns=["i", "j", "k"])
|
156 |
+
df = df.set_index(["i", "j"])
|
157 |
+
|
158 |
+
series = df.k.copy()
|
159 |
+
for i, v in zip(indexes, values):
|
160 |
+
series.iloc[i] += v
|
161 |
+
|
162 |
+
df["k"] = expected_k
|
163 |
+
expected = df.k
|
164 |
+
tm.assert_series_equal(series, expected)
|
165 |
+
|
166 |
+
|
167 |
+
def test_getitem_iloc(multiindex_dataframe_random_data):
|
168 |
+
df = multiindex_dataframe_random_data
|
169 |
+
result = df.iloc[2]
|
170 |
+
expected = df.xs(df.index[2])
|
171 |
+
tm.assert_series_equal(result, expected)
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_indexing_slow.py
ADDED
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
import pandas as pd
|
5 |
+
from pandas import (
|
6 |
+
DataFrame,
|
7 |
+
Series,
|
8 |
+
)
|
9 |
+
import pandas._testing as tm
|
10 |
+
|
11 |
+
|
12 |
+
@pytest.fixture
|
13 |
+
def m():
|
14 |
+
return 5
|
15 |
+
|
16 |
+
|
17 |
+
@pytest.fixture
|
18 |
+
def n():
|
19 |
+
return 100
|
20 |
+
|
21 |
+
|
22 |
+
@pytest.fixture
|
23 |
+
def cols():
|
24 |
+
return ["jim", "joe", "jolie", "joline", "jolia"]
|
25 |
+
|
26 |
+
|
27 |
+
@pytest.fixture
|
28 |
+
def vals(n):
|
29 |
+
vals = [
|
30 |
+
np.random.default_rng(2).integers(0, 10, n),
|
31 |
+
np.random.default_rng(2).choice(list("abcdefghij"), n),
|
32 |
+
np.random.default_rng(2).choice(
|
33 |
+
pd.date_range("20141009", periods=10).tolist(), n
|
34 |
+
),
|
35 |
+
np.random.default_rng(2).choice(list("ZYXWVUTSRQ"), n),
|
36 |
+
np.random.default_rng(2).standard_normal(n),
|
37 |
+
]
|
38 |
+
vals = list(map(tuple, zip(*vals)))
|
39 |
+
return vals
|
40 |
+
|
41 |
+
|
42 |
+
@pytest.fixture
|
43 |
+
def keys(n, m, vals):
|
44 |
+
# bunch of keys for testing
|
45 |
+
keys = [
|
46 |
+
np.random.default_rng(2).integers(0, 11, m),
|
47 |
+
np.random.default_rng(2).choice(list("abcdefghijk"), m),
|
48 |
+
np.random.default_rng(2).choice(
|
49 |
+
pd.date_range("20141009", periods=11).tolist(), m
|
50 |
+
),
|
51 |
+
np.random.default_rng(2).choice(list("ZYXWVUTSRQP"), m),
|
52 |
+
]
|
53 |
+
keys = list(map(tuple, zip(*keys)))
|
54 |
+
keys += [t[:-1] for t in vals[:: n // m]]
|
55 |
+
return keys
|
56 |
+
|
57 |
+
|
58 |
+
# covers both unique index and non-unique index
|
59 |
+
@pytest.fixture
|
60 |
+
def df(vals, cols):
|
61 |
+
return DataFrame(vals, columns=cols)
|
62 |
+
|
63 |
+
|
64 |
+
@pytest.fixture
|
65 |
+
def a(df):
|
66 |
+
return pd.concat([df, df])
|
67 |
+
|
68 |
+
|
69 |
+
@pytest.fixture
|
70 |
+
def b(df, cols):
|
71 |
+
return df.drop_duplicates(subset=cols[:-1])
|
72 |
+
|
73 |
+
|
74 |
+
@pytest.mark.filterwarnings("ignore::pandas.errors.PerformanceWarning")
|
75 |
+
@pytest.mark.parametrize("lexsort_depth", list(range(5)))
|
76 |
+
@pytest.mark.parametrize("frame_fixture", ["a", "b"])
|
77 |
+
def test_multiindex_get_loc(request, lexsort_depth, keys, frame_fixture, cols):
|
78 |
+
# GH7724, GH2646
|
79 |
+
|
80 |
+
frame = request.getfixturevalue(frame_fixture)
|
81 |
+
if lexsort_depth == 0:
|
82 |
+
df = frame.copy(deep=False)
|
83 |
+
else:
|
84 |
+
df = frame.sort_values(by=cols[:lexsort_depth])
|
85 |
+
|
86 |
+
mi = df.set_index(cols[:-1])
|
87 |
+
assert not mi.index._lexsort_depth < lexsort_depth
|
88 |
+
for key in keys:
|
89 |
+
mask = np.ones(len(df), dtype=bool)
|
90 |
+
|
91 |
+
# test for all partials of this key
|
92 |
+
for i, k in enumerate(key):
|
93 |
+
mask &= df.iloc[:, i] == k
|
94 |
+
|
95 |
+
if not mask.any():
|
96 |
+
assert key[: i + 1] not in mi.index
|
97 |
+
continue
|
98 |
+
|
99 |
+
assert key[: i + 1] in mi.index
|
100 |
+
right = df[mask].copy(deep=False)
|
101 |
+
|
102 |
+
if i + 1 != len(key): # partial key
|
103 |
+
return_value = right.drop(cols[: i + 1], axis=1, inplace=True)
|
104 |
+
assert return_value is None
|
105 |
+
return_value = right.set_index(cols[i + 1 : -1], inplace=True)
|
106 |
+
assert return_value is None
|
107 |
+
tm.assert_frame_equal(mi.loc[key[: i + 1]], right)
|
108 |
+
|
109 |
+
else: # full key
|
110 |
+
return_value = right.set_index(cols[:-1], inplace=True)
|
111 |
+
assert return_value is None
|
112 |
+
if len(right) == 1: # single hit
|
113 |
+
right = Series(
|
114 |
+
right["jolia"].values, name=right.index[0], index=["jolia"]
|
115 |
+
)
|
116 |
+
tm.assert_series_equal(mi.loc[key[: i + 1]], right)
|
117 |
+
else: # multi hit
|
118 |
+
tm.assert_frame_equal(mi.loc[key[: i + 1]], right)
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_loc.py
ADDED
@@ -0,0 +1,992 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas.errors import (
|
5 |
+
IndexingError,
|
6 |
+
PerformanceWarning,
|
7 |
+
)
|
8 |
+
|
9 |
+
import pandas as pd
|
10 |
+
from pandas import (
|
11 |
+
DataFrame,
|
12 |
+
Index,
|
13 |
+
MultiIndex,
|
14 |
+
Series,
|
15 |
+
)
|
16 |
+
import pandas._testing as tm
|
17 |
+
|
18 |
+
|
19 |
+
@pytest.fixture
|
20 |
+
def single_level_multiindex():
|
21 |
+
"""single level MultiIndex"""
|
22 |
+
return MultiIndex(
|
23 |
+
levels=[["foo", "bar", "baz", "qux"]], codes=[[0, 1, 2, 3]], names=["first"]
|
24 |
+
)
|
25 |
+
|
26 |
+
|
27 |
+
@pytest.fixture
|
28 |
+
def frame_random_data_integer_multi_index():
|
29 |
+
levels = [[0, 1], [0, 1, 2]]
|
30 |
+
codes = [[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]]
|
31 |
+
index = MultiIndex(levels=levels, codes=codes)
|
32 |
+
return DataFrame(np.random.default_rng(2).standard_normal((6, 2)), index=index)
|
33 |
+
|
34 |
+
|
35 |
+
class TestMultiIndexLoc:
|
36 |
+
def test_loc_setitem_frame_with_multiindex(self, multiindex_dataframe_random_data):
|
37 |
+
frame = multiindex_dataframe_random_data
|
38 |
+
frame.loc[("bar", "two"), "B"] = 5
|
39 |
+
assert frame.loc[("bar", "two"), "B"] == 5
|
40 |
+
|
41 |
+
# with integer labels
|
42 |
+
df = frame.copy()
|
43 |
+
df.columns = list(range(3))
|
44 |
+
df.loc[("bar", "two"), 1] = 7
|
45 |
+
assert df.loc[("bar", "two"), 1] == 7
|
46 |
+
|
47 |
+
def test_loc_getitem_general(self, any_real_numpy_dtype):
|
48 |
+
# GH#2817
|
49 |
+
dtype = any_real_numpy_dtype
|
50 |
+
data = {
|
51 |
+
"amount": {0: 700, 1: 600, 2: 222, 3: 333, 4: 444},
|
52 |
+
"col": {0: 3.5, 1: 3.5, 2: 4.0, 3: 4.0, 4: 4.0},
|
53 |
+
"num": {0: 12, 1: 11, 2: 12, 3: 12, 4: 12},
|
54 |
+
}
|
55 |
+
df = DataFrame(data)
|
56 |
+
df = df.astype({"col": dtype, "num": dtype})
|
57 |
+
df = df.set_index(keys=["col", "num"])
|
58 |
+
key = 4.0, 12
|
59 |
+
|
60 |
+
# emits a PerformanceWarning, ok
|
61 |
+
with tm.assert_produces_warning(PerformanceWarning):
|
62 |
+
tm.assert_frame_equal(df.loc[key], df.iloc[2:])
|
63 |
+
|
64 |
+
# this is ok
|
65 |
+
return_value = df.sort_index(inplace=True)
|
66 |
+
assert return_value is None
|
67 |
+
res = df.loc[key]
|
68 |
+
|
69 |
+
# col has float dtype, result should be float64 Index
|
70 |
+
col_arr = np.array([4.0] * 3, dtype=dtype)
|
71 |
+
year_arr = np.array([12] * 3, dtype=dtype)
|
72 |
+
index = MultiIndex.from_arrays([col_arr, year_arr], names=["col", "num"])
|
73 |
+
expected = DataFrame({"amount": [222, 333, 444]}, index=index)
|
74 |
+
tm.assert_frame_equal(res, expected)
|
75 |
+
|
76 |
+
def test_loc_getitem_multiindex_missing_label_raises(self):
|
77 |
+
# GH#21593
|
78 |
+
df = DataFrame(
|
79 |
+
np.random.default_rng(2).standard_normal((3, 3)),
|
80 |
+
columns=[[2, 2, 4], [6, 8, 10]],
|
81 |
+
index=[[4, 4, 8], [8, 10, 12]],
|
82 |
+
)
|
83 |
+
|
84 |
+
with pytest.raises(KeyError, match=r"^2$"):
|
85 |
+
df.loc[2]
|
86 |
+
|
87 |
+
def test_loc_getitem_list_of_tuples_with_multiindex(
|
88 |
+
self, multiindex_year_month_day_dataframe_random_data
|
89 |
+
):
|
90 |
+
ser = multiindex_year_month_day_dataframe_random_data["A"]
|
91 |
+
expected = ser.reindex(ser.index[49:51])
|
92 |
+
result = ser.loc[[(2000, 3, 10), (2000, 3, 13)]]
|
93 |
+
tm.assert_series_equal(result, expected)
|
94 |
+
|
95 |
+
def test_loc_getitem_series(self):
|
96 |
+
# GH14730
|
97 |
+
# passing a series as a key with a MultiIndex
|
98 |
+
index = MultiIndex.from_product([[1, 2, 3], ["A", "B", "C"]])
|
99 |
+
x = Series(index=index, data=range(9), dtype=np.float64)
|
100 |
+
y = Series([1, 3])
|
101 |
+
expected = Series(
|
102 |
+
data=[0, 1, 2, 6, 7, 8],
|
103 |
+
index=MultiIndex.from_product([[1, 3], ["A", "B", "C"]]),
|
104 |
+
dtype=np.float64,
|
105 |
+
)
|
106 |
+
result = x.loc[y]
|
107 |
+
tm.assert_series_equal(result, expected)
|
108 |
+
|
109 |
+
result = x.loc[[1, 3]]
|
110 |
+
tm.assert_series_equal(result, expected)
|
111 |
+
|
112 |
+
# GH15424
|
113 |
+
y1 = Series([1, 3], index=[1, 2])
|
114 |
+
result = x.loc[y1]
|
115 |
+
tm.assert_series_equal(result, expected)
|
116 |
+
|
117 |
+
empty = Series(data=[], dtype=np.float64)
|
118 |
+
expected = Series(
|
119 |
+
[],
|
120 |
+
index=MultiIndex(levels=index.levels, codes=[[], []], dtype=np.float64),
|
121 |
+
dtype=np.float64,
|
122 |
+
)
|
123 |
+
result = x.loc[empty]
|
124 |
+
tm.assert_series_equal(result, expected)
|
125 |
+
|
126 |
+
def test_loc_getitem_array(self):
|
127 |
+
# GH15434
|
128 |
+
# passing an array as a key with a MultiIndex
|
129 |
+
index = MultiIndex.from_product([[1, 2, 3], ["A", "B", "C"]])
|
130 |
+
x = Series(index=index, data=range(9), dtype=np.float64)
|
131 |
+
y = np.array([1, 3])
|
132 |
+
expected = Series(
|
133 |
+
data=[0, 1, 2, 6, 7, 8],
|
134 |
+
index=MultiIndex.from_product([[1, 3], ["A", "B", "C"]]),
|
135 |
+
dtype=np.float64,
|
136 |
+
)
|
137 |
+
result = x.loc[y]
|
138 |
+
tm.assert_series_equal(result, expected)
|
139 |
+
|
140 |
+
# empty array:
|
141 |
+
empty = np.array([])
|
142 |
+
expected = Series(
|
143 |
+
[],
|
144 |
+
index=MultiIndex(levels=index.levels, codes=[[], []], dtype=np.float64),
|
145 |
+
dtype="float64",
|
146 |
+
)
|
147 |
+
result = x.loc[empty]
|
148 |
+
tm.assert_series_equal(result, expected)
|
149 |
+
|
150 |
+
# 0-dim array (scalar):
|
151 |
+
scalar = np.int64(1)
|
152 |
+
expected = Series(data=[0, 1, 2], index=["A", "B", "C"], dtype=np.float64)
|
153 |
+
result = x.loc[scalar]
|
154 |
+
tm.assert_series_equal(result, expected)
|
155 |
+
|
156 |
+
def test_loc_multiindex_labels(self):
|
157 |
+
df = DataFrame(
|
158 |
+
np.random.default_rng(2).standard_normal((3, 3)),
|
159 |
+
columns=[["i", "i", "j"], ["A", "A", "B"]],
|
160 |
+
index=[["i", "i", "j"], ["X", "X", "Y"]],
|
161 |
+
)
|
162 |
+
|
163 |
+
# the first 2 rows
|
164 |
+
expected = df.iloc[[0, 1]].droplevel(0)
|
165 |
+
result = df.loc["i"]
|
166 |
+
tm.assert_frame_equal(result, expected)
|
167 |
+
|
168 |
+
# 2nd (last) column
|
169 |
+
expected = df.iloc[:, [2]].droplevel(0, axis=1)
|
170 |
+
result = df.loc[:, "j"]
|
171 |
+
tm.assert_frame_equal(result, expected)
|
172 |
+
|
173 |
+
# bottom right corner
|
174 |
+
expected = df.iloc[[2], [2]].droplevel(0).droplevel(0, axis=1)
|
175 |
+
result = df.loc["j"].loc[:, "j"]
|
176 |
+
tm.assert_frame_equal(result, expected)
|
177 |
+
|
178 |
+
# with a tuple
|
179 |
+
expected = df.iloc[[0, 1]]
|
180 |
+
result = df.loc[("i", "X")]
|
181 |
+
tm.assert_frame_equal(result, expected)
|
182 |
+
|
183 |
+
def test_loc_multiindex_ints(self):
|
184 |
+
df = DataFrame(
|
185 |
+
np.random.default_rng(2).standard_normal((3, 3)),
|
186 |
+
columns=[[2, 2, 4], [6, 8, 10]],
|
187 |
+
index=[[4, 4, 8], [8, 10, 12]],
|
188 |
+
)
|
189 |
+
expected = df.iloc[[0, 1]].droplevel(0)
|
190 |
+
result = df.loc[4]
|
191 |
+
tm.assert_frame_equal(result, expected)
|
192 |
+
|
193 |
+
def test_loc_multiindex_missing_label_raises(self):
|
194 |
+
df = DataFrame(
|
195 |
+
np.random.default_rng(2).standard_normal((3, 3)),
|
196 |
+
columns=[[2, 2, 4], [6, 8, 10]],
|
197 |
+
index=[[4, 4, 8], [8, 10, 12]],
|
198 |
+
)
|
199 |
+
|
200 |
+
with pytest.raises(KeyError, match=r"^2$"):
|
201 |
+
df.loc[2]
|
202 |
+
|
203 |
+
@pytest.mark.parametrize("key, pos", [([2, 4], [0, 1]), ([2], []), ([2, 3], [])])
|
204 |
+
def test_loc_multiindex_list_missing_label(self, key, pos):
|
205 |
+
# GH 27148 - lists with missing labels _do_ raise
|
206 |
+
df = DataFrame(
|
207 |
+
np.random.default_rng(2).standard_normal((3, 3)),
|
208 |
+
columns=[[2, 2, 4], [6, 8, 10]],
|
209 |
+
index=[[4, 4, 8], [8, 10, 12]],
|
210 |
+
)
|
211 |
+
|
212 |
+
with pytest.raises(KeyError, match="not in index"):
|
213 |
+
df.loc[key]
|
214 |
+
|
215 |
+
def test_loc_multiindex_too_many_dims_raises(self):
|
216 |
+
# GH 14885
|
217 |
+
s = Series(
|
218 |
+
range(8),
|
219 |
+
index=MultiIndex.from_product([["a", "b"], ["c", "d"], ["e", "f"]]),
|
220 |
+
)
|
221 |
+
|
222 |
+
with pytest.raises(KeyError, match=r"^\('a', 'b'\)$"):
|
223 |
+
s.loc["a", "b"]
|
224 |
+
with pytest.raises(KeyError, match=r"^\('a', 'd', 'g'\)$"):
|
225 |
+
s.loc["a", "d", "g"]
|
226 |
+
with pytest.raises(IndexingError, match="Too many indexers"):
|
227 |
+
s.loc["a", "d", "g", "j"]
|
228 |
+
|
229 |
+
def test_loc_multiindex_indexer_none(self):
|
230 |
+
# GH6788
|
231 |
+
# multi-index indexer is None (meaning take all)
|
232 |
+
attributes = ["Attribute" + str(i) for i in range(1)]
|
233 |
+
attribute_values = ["Value" + str(i) for i in range(5)]
|
234 |
+
|
235 |
+
index = MultiIndex.from_product([attributes, attribute_values])
|
236 |
+
df = 0.1 * np.random.default_rng(2).standard_normal((10, 1 * 5)) + 0.5
|
237 |
+
df = DataFrame(df, columns=index)
|
238 |
+
result = df[attributes]
|
239 |
+
tm.assert_frame_equal(result, df)
|
240 |
+
|
241 |
+
# GH 7349
|
242 |
+
# loc with a multi-index seems to be doing fallback
|
243 |
+
df = DataFrame(
|
244 |
+
np.arange(12).reshape(-1, 1),
|
245 |
+
index=MultiIndex.from_product([[1, 2, 3, 4], [1, 2, 3]]),
|
246 |
+
)
|
247 |
+
|
248 |
+
expected = df.loc[([1, 2],), :]
|
249 |
+
result = df.loc[[1, 2]]
|
250 |
+
tm.assert_frame_equal(result, expected)
|
251 |
+
|
252 |
+
def test_loc_multiindex_incomplete(self):
|
253 |
+
# GH 7399
|
254 |
+
# incomplete indexers
|
255 |
+
s = Series(
|
256 |
+
np.arange(15, dtype="int64"),
|
257 |
+
MultiIndex.from_product([range(5), ["a", "b", "c"]]),
|
258 |
+
)
|
259 |
+
expected = s.loc[:, "a":"c"]
|
260 |
+
|
261 |
+
result = s.loc[0:4, "a":"c"]
|
262 |
+
tm.assert_series_equal(result, expected)
|
263 |
+
|
264 |
+
result = s.loc[:4, "a":"c"]
|
265 |
+
tm.assert_series_equal(result, expected)
|
266 |
+
|
267 |
+
result = s.loc[0:, "a":"c"]
|
268 |
+
tm.assert_series_equal(result, expected)
|
269 |
+
|
270 |
+
# GH 7400
|
271 |
+
# multiindexer getitem with list of indexers skips wrong element
|
272 |
+
s = Series(
|
273 |
+
np.arange(15, dtype="int64"),
|
274 |
+
MultiIndex.from_product([range(5), ["a", "b", "c"]]),
|
275 |
+
)
|
276 |
+
expected = s.iloc[[6, 7, 8, 12, 13, 14]]
|
277 |
+
result = s.loc[2:4:2, "a":"c"]
|
278 |
+
tm.assert_series_equal(result, expected)
|
279 |
+
|
280 |
+
def test_get_loc_single_level(self, single_level_multiindex):
|
281 |
+
single_level = single_level_multiindex
|
282 |
+
s = Series(
|
283 |
+
np.random.default_rng(2).standard_normal(len(single_level)),
|
284 |
+
index=single_level,
|
285 |
+
)
|
286 |
+
for k in single_level.values:
|
287 |
+
s[k]
|
288 |
+
|
289 |
+
def test_loc_getitem_int_slice(self):
|
290 |
+
# GH 3053
|
291 |
+
# loc should treat integer slices like label slices
|
292 |
+
|
293 |
+
index = MultiIndex.from_product([[6, 7, 8], ["a", "b"]])
|
294 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((6, 6)), index, index)
|
295 |
+
result = df.loc[6:8, :]
|
296 |
+
expected = df
|
297 |
+
tm.assert_frame_equal(result, expected)
|
298 |
+
|
299 |
+
index = MultiIndex.from_product([[10, 20, 30], ["a", "b"]])
|
300 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((6, 6)), index, index)
|
301 |
+
result = df.loc[20:30, :]
|
302 |
+
expected = df.iloc[2:]
|
303 |
+
tm.assert_frame_equal(result, expected)
|
304 |
+
|
305 |
+
# doc examples
|
306 |
+
result = df.loc[10, :]
|
307 |
+
expected = df.iloc[0:2]
|
308 |
+
expected.index = ["a", "b"]
|
309 |
+
tm.assert_frame_equal(result, expected)
|
310 |
+
|
311 |
+
result = df.loc[:, 10]
|
312 |
+
expected = df[10]
|
313 |
+
tm.assert_frame_equal(result, expected)
|
314 |
+
|
315 |
+
@pytest.mark.parametrize(
|
316 |
+
"indexer_type_1", (list, tuple, set, slice, np.ndarray, Series, Index)
|
317 |
+
)
|
318 |
+
@pytest.mark.parametrize(
|
319 |
+
"indexer_type_2", (list, tuple, set, slice, np.ndarray, Series, Index)
|
320 |
+
)
|
321 |
+
def test_loc_getitem_nested_indexer(self, indexer_type_1, indexer_type_2):
|
322 |
+
# GH #19686
|
323 |
+
# .loc should work with nested indexers which can be
|
324 |
+
# any list-like objects (see `is_list_like` (`pandas.api.types`)) or slices
|
325 |
+
|
326 |
+
def convert_nested_indexer(indexer_type, keys):
|
327 |
+
if indexer_type == np.ndarray:
|
328 |
+
return np.array(keys)
|
329 |
+
if indexer_type == slice:
|
330 |
+
return slice(*keys)
|
331 |
+
return indexer_type(keys)
|
332 |
+
|
333 |
+
a = [10, 20, 30]
|
334 |
+
b = [1, 2, 3]
|
335 |
+
index = MultiIndex.from_product([a, b])
|
336 |
+
df = DataFrame(
|
337 |
+
np.arange(len(index), dtype="int64"), index=index, columns=["Data"]
|
338 |
+
)
|
339 |
+
|
340 |
+
keys = ([10, 20], [2, 3])
|
341 |
+
types = (indexer_type_1, indexer_type_2)
|
342 |
+
|
343 |
+
# check indexers with all the combinations of nested objects
|
344 |
+
# of all the valid types
|
345 |
+
indexer = tuple(
|
346 |
+
convert_nested_indexer(indexer_type, k)
|
347 |
+
for indexer_type, k in zip(types, keys)
|
348 |
+
)
|
349 |
+
if indexer_type_1 is set or indexer_type_2 is set:
|
350 |
+
with pytest.raises(TypeError, match="as an indexer is not supported"):
|
351 |
+
df.loc[indexer, "Data"]
|
352 |
+
|
353 |
+
return
|
354 |
+
else:
|
355 |
+
result = df.loc[indexer, "Data"]
|
356 |
+
expected = Series(
|
357 |
+
[1, 2, 4, 5], name="Data", index=MultiIndex.from_product(keys)
|
358 |
+
)
|
359 |
+
|
360 |
+
tm.assert_series_equal(result, expected)
|
361 |
+
|
362 |
+
def test_multiindex_loc_one_dimensional_tuple(self, frame_or_series):
|
363 |
+
# GH#37711
|
364 |
+
mi = MultiIndex.from_tuples([("a", "A"), ("b", "A")])
|
365 |
+
obj = frame_or_series([1, 2], index=mi)
|
366 |
+
obj.loc[("a",)] = 0
|
367 |
+
expected = frame_or_series([0, 2], index=mi)
|
368 |
+
tm.assert_equal(obj, expected)
|
369 |
+
|
370 |
+
@pytest.mark.parametrize("indexer", [("a",), ("a")])
|
371 |
+
def test_multiindex_one_dimensional_tuple_columns(self, indexer):
|
372 |
+
# GH#37711
|
373 |
+
mi = MultiIndex.from_tuples([("a", "A"), ("b", "A")])
|
374 |
+
obj = DataFrame([1, 2], index=mi)
|
375 |
+
obj.loc[indexer, :] = 0
|
376 |
+
expected = DataFrame([0, 2], index=mi)
|
377 |
+
tm.assert_frame_equal(obj, expected)
|
378 |
+
|
379 |
+
@pytest.mark.parametrize(
|
380 |
+
"indexer, exp_value", [(slice(None), 1.0), ((1, 2), np.nan)]
|
381 |
+
)
|
382 |
+
def test_multiindex_setitem_columns_enlarging(self, indexer, exp_value):
|
383 |
+
# GH#39147
|
384 |
+
mi = MultiIndex.from_tuples([(1, 2), (3, 4)])
|
385 |
+
df = DataFrame([[1, 2], [3, 4]], index=mi, columns=["a", "b"])
|
386 |
+
df.loc[indexer, ["c", "d"]] = 1.0
|
387 |
+
expected = DataFrame(
|
388 |
+
[[1, 2, 1.0, 1.0], [3, 4, exp_value, exp_value]],
|
389 |
+
index=mi,
|
390 |
+
columns=["a", "b", "c", "d"],
|
391 |
+
)
|
392 |
+
tm.assert_frame_equal(df, expected)
|
393 |
+
|
394 |
+
def test_sorted_multiindex_after_union(self):
|
395 |
+
# GH#44752
|
396 |
+
midx = MultiIndex.from_product(
|
397 |
+
[pd.date_range("20110101", periods=2), Index(["a", "b"])]
|
398 |
+
)
|
399 |
+
ser1 = Series(1, index=midx)
|
400 |
+
ser2 = Series(1, index=midx[:2])
|
401 |
+
df = pd.concat([ser1, ser2], axis=1)
|
402 |
+
expected = df.copy()
|
403 |
+
result = df.loc["2011-01-01":"2011-01-02"]
|
404 |
+
tm.assert_frame_equal(result, expected)
|
405 |
+
|
406 |
+
df = DataFrame({0: ser1, 1: ser2})
|
407 |
+
result = df.loc["2011-01-01":"2011-01-02"]
|
408 |
+
tm.assert_frame_equal(result, expected)
|
409 |
+
|
410 |
+
df = pd.concat([ser1, ser2.reindex(ser1.index)], axis=1)
|
411 |
+
result = df.loc["2011-01-01":"2011-01-02"]
|
412 |
+
tm.assert_frame_equal(result, expected)
|
413 |
+
|
414 |
+
def test_loc_no_second_level_index(self):
|
415 |
+
# GH#43599
|
416 |
+
df = DataFrame(
|
417 |
+
index=MultiIndex.from_product([list("ab"), list("cd"), list("e")]),
|
418 |
+
columns=["Val"],
|
419 |
+
)
|
420 |
+
res = df.loc[np.s_[:, "c", :]]
|
421 |
+
expected = DataFrame(
|
422 |
+
index=MultiIndex.from_product([list("ab"), list("e")]), columns=["Val"]
|
423 |
+
)
|
424 |
+
tm.assert_frame_equal(res, expected)
|
425 |
+
|
426 |
+
def test_loc_multi_index_key_error(self):
|
427 |
+
# GH 51892
|
428 |
+
df = DataFrame(
|
429 |
+
{
|
430 |
+
(1, 2): ["a", "b", "c"],
|
431 |
+
(1, 3): ["d", "e", "f"],
|
432 |
+
(2, 2): ["g", "h", "i"],
|
433 |
+
(2, 4): ["j", "k", "l"],
|
434 |
+
}
|
435 |
+
)
|
436 |
+
with pytest.raises(KeyError, match=r"(1, 4)"):
|
437 |
+
df.loc[0, (1, 4)]
|
438 |
+
|
439 |
+
|
440 |
+
@pytest.mark.parametrize(
|
441 |
+
"indexer, pos",
|
442 |
+
[
|
443 |
+
([], []), # empty ok
|
444 |
+
(["A"], slice(3)),
|
445 |
+
(["A", "D"], []), # "D" isn't present -> raise
|
446 |
+
(["D", "E"], []), # no values found -> raise
|
447 |
+
(["D"], []), # same, with single item list: GH 27148
|
448 |
+
(pd.IndexSlice[:, ["foo"]], slice(2, None, 3)),
|
449 |
+
(pd.IndexSlice[:, ["foo", "bah"]], slice(2, None, 3)),
|
450 |
+
],
|
451 |
+
)
|
452 |
+
def test_loc_getitem_duplicates_multiindex_missing_indexers(indexer, pos):
|
453 |
+
# GH 7866
|
454 |
+
# multi-index slicing with missing indexers
|
455 |
+
idx = MultiIndex.from_product(
|
456 |
+
[["A", "B", "C"], ["foo", "bar", "baz"]], names=["one", "two"]
|
457 |
+
)
|
458 |
+
ser = Series(np.arange(9, dtype="int64"), index=idx).sort_index()
|
459 |
+
expected = ser.iloc[pos]
|
460 |
+
|
461 |
+
if expected.size == 0 and indexer != []:
|
462 |
+
with pytest.raises(KeyError, match=str(indexer)):
|
463 |
+
ser.loc[indexer]
|
464 |
+
elif indexer == (slice(None), ["foo", "bah"]):
|
465 |
+
# "bah" is not in idx.levels[1], raising KeyError enforced in 2.0
|
466 |
+
with pytest.raises(KeyError, match="'bah'"):
|
467 |
+
ser.loc[indexer]
|
468 |
+
else:
|
469 |
+
result = ser.loc[indexer]
|
470 |
+
tm.assert_series_equal(result, expected)
|
471 |
+
|
472 |
+
|
473 |
+
@pytest.mark.parametrize("columns_indexer", [([], slice(None)), (["foo"], [])])
|
474 |
+
def test_loc_getitem_duplicates_multiindex_empty_indexer(columns_indexer):
|
475 |
+
# GH 8737
|
476 |
+
# empty indexer
|
477 |
+
multi_index = MultiIndex.from_product((["foo", "bar", "baz"], ["alpha", "beta"]))
|
478 |
+
df = DataFrame(
|
479 |
+
np.random.default_rng(2).standard_normal((5, 6)),
|
480 |
+
index=range(5),
|
481 |
+
columns=multi_index,
|
482 |
+
)
|
483 |
+
df = df.sort_index(level=0, axis=1)
|
484 |
+
|
485 |
+
expected = DataFrame(index=range(5), columns=multi_index.reindex([])[0])
|
486 |
+
result = df.loc[:, columns_indexer]
|
487 |
+
tm.assert_frame_equal(result, expected)
|
488 |
+
|
489 |
+
|
490 |
+
def test_loc_getitem_duplicates_multiindex_non_scalar_type_object():
|
491 |
+
# regression from < 0.14.0
|
492 |
+
# GH 7914
|
493 |
+
df = DataFrame(
|
494 |
+
[[np.mean, np.median], ["mean", "median"]],
|
495 |
+
columns=MultiIndex.from_tuples([("functs", "mean"), ("functs", "median")]),
|
496 |
+
index=["function", "name"],
|
497 |
+
)
|
498 |
+
result = df.loc["function", ("functs", "mean")]
|
499 |
+
expected = np.mean
|
500 |
+
assert result == expected
|
501 |
+
|
502 |
+
|
503 |
+
def test_loc_getitem_tuple_plus_slice():
|
504 |
+
# GH 671
|
505 |
+
df = DataFrame(
|
506 |
+
{
|
507 |
+
"a": np.arange(10),
|
508 |
+
"b": np.arange(10),
|
509 |
+
"c": np.random.default_rng(2).standard_normal(10),
|
510 |
+
"d": np.random.default_rng(2).standard_normal(10),
|
511 |
+
}
|
512 |
+
).set_index(["a", "b"])
|
513 |
+
expected = df.loc[0, 0]
|
514 |
+
result = df.loc[(0, 0), :]
|
515 |
+
tm.assert_series_equal(result, expected)
|
516 |
+
|
517 |
+
|
518 |
+
def test_loc_getitem_int(frame_random_data_integer_multi_index):
|
519 |
+
df = frame_random_data_integer_multi_index
|
520 |
+
result = df.loc[1]
|
521 |
+
expected = df[-3:]
|
522 |
+
expected.index = expected.index.droplevel(0)
|
523 |
+
tm.assert_frame_equal(result, expected)
|
524 |
+
|
525 |
+
|
526 |
+
def test_loc_getitem_int_raises_exception(frame_random_data_integer_multi_index):
|
527 |
+
df = frame_random_data_integer_multi_index
|
528 |
+
with pytest.raises(KeyError, match=r"^3$"):
|
529 |
+
df.loc[3]
|
530 |
+
|
531 |
+
|
532 |
+
def test_loc_getitem_lowerdim_corner(multiindex_dataframe_random_data):
|
533 |
+
df = multiindex_dataframe_random_data
|
534 |
+
|
535 |
+
# test setup - check key not in dataframe
|
536 |
+
with pytest.raises(KeyError, match=r"^\('bar', 'three'\)$"):
|
537 |
+
df.loc[("bar", "three"), "B"]
|
538 |
+
|
539 |
+
# in theory should be inserting in a sorted space????
|
540 |
+
df.loc[("bar", "three"), "B"] = 0
|
541 |
+
expected = 0
|
542 |
+
result = df.sort_index().loc[("bar", "three"), "B"]
|
543 |
+
assert result == expected
|
544 |
+
|
545 |
+
|
546 |
+
def test_loc_setitem_single_column_slice():
|
547 |
+
# case from https://github.com/pandas-dev/pandas/issues/27841
|
548 |
+
df = DataFrame(
|
549 |
+
"string",
|
550 |
+
index=list("abcd"),
|
551 |
+
columns=MultiIndex.from_product([["Main"], ("another", "one")]),
|
552 |
+
)
|
553 |
+
df["labels"] = "a"
|
554 |
+
df.loc[:, "labels"] = df.index
|
555 |
+
tm.assert_numpy_array_equal(np.asarray(df["labels"]), np.asarray(df.index))
|
556 |
+
|
557 |
+
# test with non-object block
|
558 |
+
df = DataFrame(
|
559 |
+
np.nan,
|
560 |
+
index=range(4),
|
561 |
+
columns=MultiIndex.from_tuples([("A", "1"), ("A", "2"), ("B", "1")]),
|
562 |
+
)
|
563 |
+
expected = df.copy()
|
564 |
+
df.loc[:, "B"] = np.arange(4)
|
565 |
+
expected.iloc[:, 2] = np.arange(4)
|
566 |
+
tm.assert_frame_equal(df, expected)
|
567 |
+
|
568 |
+
|
569 |
+
def test_loc_nan_multiindex(using_infer_string):
|
570 |
+
# GH 5286
|
571 |
+
tups = [
|
572 |
+
("Good Things", "C", np.nan),
|
573 |
+
("Good Things", "R", np.nan),
|
574 |
+
("Bad Things", "C", np.nan),
|
575 |
+
("Bad Things", "T", np.nan),
|
576 |
+
("Okay Things", "N", "B"),
|
577 |
+
("Okay Things", "N", "D"),
|
578 |
+
("Okay Things", "B", np.nan),
|
579 |
+
("Okay Things", "D", np.nan),
|
580 |
+
]
|
581 |
+
df = DataFrame(
|
582 |
+
np.ones((8, 4)),
|
583 |
+
columns=Index(["d1", "d2", "d3", "d4"]),
|
584 |
+
index=MultiIndex.from_tuples(tups, names=["u1", "u2", "u3"]),
|
585 |
+
)
|
586 |
+
result = df.loc["Good Things"].loc["C"]
|
587 |
+
expected = DataFrame(
|
588 |
+
np.ones((1, 4)),
|
589 |
+
index=Index(
|
590 |
+
[np.nan],
|
591 |
+
dtype="object" if not using_infer_string else "string[pyarrow_numpy]",
|
592 |
+
name="u3",
|
593 |
+
),
|
594 |
+
columns=Index(["d1", "d2", "d3", "d4"]),
|
595 |
+
)
|
596 |
+
tm.assert_frame_equal(result, expected)
|
597 |
+
|
598 |
+
|
599 |
+
def test_loc_period_string_indexing():
|
600 |
+
# GH 9892
|
601 |
+
a = pd.period_range("2013Q1", "2013Q4", freq="Q")
|
602 |
+
i = (1111, 2222, 3333)
|
603 |
+
idx = MultiIndex.from_product((a, i), names=("Period", "CVR"))
|
604 |
+
df = DataFrame(
|
605 |
+
index=idx,
|
606 |
+
columns=(
|
607 |
+
"OMS",
|
608 |
+
"OMK",
|
609 |
+
"RES",
|
610 |
+
"DRIFT_IND",
|
611 |
+
"OEVRIG_IND",
|
612 |
+
"FIN_IND",
|
613 |
+
"VARE_UD",
|
614 |
+
"LOEN_UD",
|
615 |
+
"FIN_UD",
|
616 |
+
),
|
617 |
+
)
|
618 |
+
result = df.loc[("2013Q1", 1111), "OMS"]
|
619 |
+
|
620 |
+
alt = df.loc[(a[0], 1111), "OMS"]
|
621 |
+
assert np.isnan(alt)
|
622 |
+
|
623 |
+
# Because the resolution of the string matches, it is an exact lookup,
|
624 |
+
# not a slice
|
625 |
+
assert np.isnan(result)
|
626 |
+
|
627 |
+
alt = df.loc[("2013Q1", 1111), "OMS"]
|
628 |
+
assert np.isnan(alt)
|
629 |
+
|
630 |
+
|
631 |
+
def test_loc_datetime_mask_slicing():
|
632 |
+
# GH 16699
|
633 |
+
dt_idx = pd.to_datetime(["2017-05-04", "2017-05-05"])
|
634 |
+
m_idx = MultiIndex.from_product([dt_idx, dt_idx], names=["Idx1", "Idx2"])
|
635 |
+
df = DataFrame(
|
636 |
+
data=[[1, 2], [3, 4], [5, 6], [7, 6]], index=m_idx, columns=["C1", "C2"]
|
637 |
+
)
|
638 |
+
result = df.loc[(dt_idx[0], (df.index.get_level_values(1) > "2017-05-04")), "C1"]
|
639 |
+
expected = Series(
|
640 |
+
[3],
|
641 |
+
name="C1",
|
642 |
+
index=MultiIndex.from_tuples(
|
643 |
+
[(pd.Timestamp("2017-05-04"), pd.Timestamp("2017-05-05"))],
|
644 |
+
names=["Idx1", "Idx2"],
|
645 |
+
),
|
646 |
+
)
|
647 |
+
tm.assert_series_equal(result, expected)
|
648 |
+
|
649 |
+
|
650 |
+
def test_loc_datetime_series_tuple_slicing():
|
651 |
+
# https://github.com/pandas-dev/pandas/issues/35858
|
652 |
+
date = pd.Timestamp("2000")
|
653 |
+
ser = Series(
|
654 |
+
1,
|
655 |
+
index=MultiIndex.from_tuples([("a", date)], names=["a", "b"]),
|
656 |
+
name="c",
|
657 |
+
)
|
658 |
+
result = ser.loc[:, [date]]
|
659 |
+
tm.assert_series_equal(result, ser)
|
660 |
+
|
661 |
+
|
662 |
+
def test_loc_with_mi_indexer():
|
663 |
+
# https://github.com/pandas-dev/pandas/issues/35351
|
664 |
+
df = DataFrame(
|
665 |
+
data=[["a", 1], ["a", 0], ["b", 1], ["c", 2]],
|
666 |
+
index=MultiIndex.from_tuples(
|
667 |
+
[(0, 1), (1, 0), (1, 1), (1, 1)], names=["index", "date"]
|
668 |
+
),
|
669 |
+
columns=["author", "price"],
|
670 |
+
)
|
671 |
+
idx = MultiIndex.from_tuples([(0, 1), (1, 1)], names=["index", "date"])
|
672 |
+
result = df.loc[idx, :]
|
673 |
+
expected = DataFrame(
|
674 |
+
[["a", 1], ["b", 1], ["c", 2]],
|
675 |
+
index=MultiIndex.from_tuples([(0, 1), (1, 1), (1, 1)], names=["index", "date"]),
|
676 |
+
columns=["author", "price"],
|
677 |
+
)
|
678 |
+
tm.assert_frame_equal(result, expected)
|
679 |
+
|
680 |
+
|
681 |
+
def test_loc_mi_with_level1_named_0():
|
682 |
+
# GH#37194
|
683 |
+
dti = pd.date_range("2016-01-01", periods=3, tz="US/Pacific")
|
684 |
+
|
685 |
+
ser = Series(range(3), index=dti)
|
686 |
+
df = ser.to_frame()
|
687 |
+
df[1] = dti
|
688 |
+
|
689 |
+
df2 = df.set_index(0, append=True)
|
690 |
+
assert df2.index.names == (None, 0)
|
691 |
+
df2.index.get_loc(dti[0]) # smoke test
|
692 |
+
|
693 |
+
result = df2.loc[dti[0]]
|
694 |
+
expected = df2.iloc[[0]].droplevel(None)
|
695 |
+
tm.assert_frame_equal(result, expected)
|
696 |
+
|
697 |
+
ser2 = df2[1]
|
698 |
+
assert ser2.index.names == (None, 0)
|
699 |
+
|
700 |
+
result = ser2.loc[dti[0]]
|
701 |
+
expected = ser2.iloc[[0]].droplevel(None)
|
702 |
+
tm.assert_series_equal(result, expected)
|
703 |
+
|
704 |
+
|
705 |
+
def test_getitem_str_slice():
|
706 |
+
# GH#15928
|
707 |
+
df = DataFrame(
|
708 |
+
[
|
709 |
+
["20160525 13:30:00.023", "MSFT", "51.95", "51.95"],
|
710 |
+
["20160525 13:30:00.048", "GOOG", "720.50", "720.93"],
|
711 |
+
["20160525 13:30:00.076", "AAPL", "98.55", "98.56"],
|
712 |
+
["20160525 13:30:00.131", "AAPL", "98.61", "98.62"],
|
713 |
+
["20160525 13:30:00.135", "MSFT", "51.92", "51.95"],
|
714 |
+
["20160525 13:30:00.135", "AAPL", "98.61", "98.62"],
|
715 |
+
],
|
716 |
+
columns="time,ticker,bid,ask".split(","),
|
717 |
+
)
|
718 |
+
df2 = df.set_index(["ticker", "time"]).sort_index()
|
719 |
+
|
720 |
+
res = df2.loc[("AAPL", slice("2016-05-25 13:30:00")), :].droplevel(0)
|
721 |
+
expected = df2.loc["AAPL"].loc[slice("2016-05-25 13:30:00"), :]
|
722 |
+
tm.assert_frame_equal(res, expected)
|
723 |
+
|
724 |
+
|
725 |
+
def test_3levels_leading_period_index():
|
726 |
+
# GH#24091
|
727 |
+
pi = pd.PeriodIndex(
|
728 |
+
["20181101 1100", "20181101 1200", "20181102 1300", "20181102 1400"],
|
729 |
+
name="datetime",
|
730 |
+
freq="D",
|
731 |
+
)
|
732 |
+
lev2 = ["A", "A", "Z", "W"]
|
733 |
+
lev3 = ["B", "C", "Q", "F"]
|
734 |
+
mi = MultiIndex.from_arrays([pi, lev2, lev3])
|
735 |
+
|
736 |
+
ser = Series(range(4), index=mi, dtype=np.float64)
|
737 |
+
result = ser.loc[(pi[0], "A", "B")]
|
738 |
+
assert result == 0.0
|
739 |
+
|
740 |
+
|
741 |
+
class TestKeyErrorsWithMultiIndex:
|
742 |
+
def test_missing_keys_raises_keyerror(self):
|
743 |
+
# GH#27420 KeyError, not TypeError
|
744 |
+
df = DataFrame(np.arange(12).reshape(4, 3), columns=["A", "B", "C"])
|
745 |
+
df2 = df.set_index(["A", "B"])
|
746 |
+
|
747 |
+
with pytest.raises(KeyError, match="1"):
|
748 |
+
df2.loc[(1, 6)]
|
749 |
+
|
750 |
+
def test_missing_key_raises_keyerror2(self):
|
751 |
+
# GH#21168 KeyError, not "IndexingError: Too many indexers"
|
752 |
+
ser = Series(-1, index=MultiIndex.from_product([[0, 1]] * 2))
|
753 |
+
|
754 |
+
with pytest.raises(KeyError, match=r"\(0, 3\)"):
|
755 |
+
ser.loc[0, 3]
|
756 |
+
|
757 |
+
def test_missing_key_combination(self):
|
758 |
+
# GH: 19556
|
759 |
+
mi = MultiIndex.from_arrays(
|
760 |
+
[
|
761 |
+
np.array(["a", "a", "b", "b"]),
|
762 |
+
np.array(["1", "2", "2", "3"]),
|
763 |
+
np.array(["c", "d", "c", "d"]),
|
764 |
+
],
|
765 |
+
names=["one", "two", "three"],
|
766 |
+
)
|
767 |
+
df = DataFrame(np.random.default_rng(2).random((4, 3)), index=mi)
|
768 |
+
msg = r"\('b', '1', slice\(None, None, None\)\)"
|
769 |
+
with pytest.raises(KeyError, match=msg):
|
770 |
+
df.loc[("b", "1", slice(None)), :]
|
771 |
+
with pytest.raises(KeyError, match=msg):
|
772 |
+
df.index.get_locs(("b", "1", slice(None)))
|
773 |
+
with pytest.raises(KeyError, match=r"\('b', '1'\)"):
|
774 |
+
df.loc[("b", "1"), :]
|
775 |
+
|
776 |
+
|
777 |
+
def test_getitem_loc_commutability(multiindex_year_month_day_dataframe_random_data):
|
778 |
+
df = multiindex_year_month_day_dataframe_random_data
|
779 |
+
ser = df["A"]
|
780 |
+
result = ser[2000, 5]
|
781 |
+
expected = df.loc[2000, 5]["A"]
|
782 |
+
tm.assert_series_equal(result, expected)
|
783 |
+
|
784 |
+
|
785 |
+
def test_loc_with_nan():
|
786 |
+
# GH: 27104
|
787 |
+
df = DataFrame(
|
788 |
+
{"col": [1, 2, 5], "ind1": ["a", "d", np.nan], "ind2": [1, 4, 5]}
|
789 |
+
).set_index(["ind1", "ind2"])
|
790 |
+
result = df.loc[["a"]]
|
791 |
+
expected = DataFrame(
|
792 |
+
{"col": [1]}, index=MultiIndex.from_tuples([("a", 1)], names=["ind1", "ind2"])
|
793 |
+
)
|
794 |
+
tm.assert_frame_equal(result, expected)
|
795 |
+
|
796 |
+
result = df.loc["a"]
|
797 |
+
expected = DataFrame({"col": [1]}, index=Index([1], name="ind2"))
|
798 |
+
tm.assert_frame_equal(result, expected)
|
799 |
+
|
800 |
+
|
801 |
+
def test_getitem_non_found_tuple():
|
802 |
+
# GH: 25236
|
803 |
+
df = DataFrame([[1, 2, 3, 4]], columns=["a", "b", "c", "d"]).set_index(
|
804 |
+
["a", "b", "c"]
|
805 |
+
)
|
806 |
+
with pytest.raises(KeyError, match=r"\(2\.0, 2\.0, 3\.0\)"):
|
807 |
+
df.loc[(2.0, 2.0, 3.0)]
|
808 |
+
|
809 |
+
|
810 |
+
def test_get_loc_datetime_index():
|
811 |
+
# GH#24263
|
812 |
+
index = pd.date_range("2001-01-01", periods=100)
|
813 |
+
mi = MultiIndex.from_arrays([index])
|
814 |
+
# Check if get_loc matches for Index and MultiIndex
|
815 |
+
assert mi.get_loc("2001-01") == slice(0, 31, None)
|
816 |
+
assert index.get_loc("2001-01") == slice(0, 31, None)
|
817 |
+
|
818 |
+
loc = mi[::2].get_loc("2001-01")
|
819 |
+
expected = index[::2].get_loc("2001-01")
|
820 |
+
assert loc == expected
|
821 |
+
|
822 |
+
loc = mi.repeat(2).get_loc("2001-01")
|
823 |
+
expected = index.repeat(2).get_loc("2001-01")
|
824 |
+
assert loc == expected
|
825 |
+
|
826 |
+
loc = mi.append(mi).get_loc("2001-01")
|
827 |
+
expected = index.append(index).get_loc("2001-01")
|
828 |
+
# TODO: standardize return type for MultiIndex.get_loc
|
829 |
+
tm.assert_numpy_array_equal(loc.nonzero()[0], expected)
|
830 |
+
|
831 |
+
|
832 |
+
def test_loc_setitem_indexer_differently_ordered():
|
833 |
+
# GH#34603
|
834 |
+
mi = MultiIndex.from_product([["a", "b"], [0, 1]])
|
835 |
+
df = DataFrame([[1, 2], [3, 4], [5, 6], [7, 8]], index=mi)
|
836 |
+
|
837 |
+
indexer = ("a", [1, 0])
|
838 |
+
df.loc[indexer, :] = np.array([[9, 10], [11, 12]])
|
839 |
+
expected = DataFrame([[11, 12], [9, 10], [5, 6], [7, 8]], index=mi)
|
840 |
+
tm.assert_frame_equal(df, expected)
|
841 |
+
|
842 |
+
|
843 |
+
def test_loc_getitem_index_differently_ordered_slice_none():
|
844 |
+
# GH#31330
|
845 |
+
df = DataFrame(
|
846 |
+
[[1, 2], [3, 4], [5, 6], [7, 8]],
|
847 |
+
index=[["a", "a", "b", "b"], [1, 2, 1, 2]],
|
848 |
+
columns=["a", "b"],
|
849 |
+
)
|
850 |
+
result = df.loc[(slice(None), [2, 1]), :]
|
851 |
+
expected = DataFrame(
|
852 |
+
[[3, 4], [7, 8], [1, 2], [5, 6]],
|
853 |
+
index=[["a", "b", "a", "b"], [2, 2, 1, 1]],
|
854 |
+
columns=["a", "b"],
|
855 |
+
)
|
856 |
+
tm.assert_frame_equal(result, expected)
|
857 |
+
|
858 |
+
|
859 |
+
@pytest.mark.parametrize("indexer", [[1, 2, 7, 6, 2, 3, 8, 7], [1, 2, 7, 6, 3, 8]])
|
860 |
+
def test_loc_getitem_index_differently_ordered_slice_none_duplicates(indexer):
|
861 |
+
# GH#40978
|
862 |
+
df = DataFrame(
|
863 |
+
[1] * 8,
|
864 |
+
index=MultiIndex.from_tuples(
|
865 |
+
[(1, 1), (1, 2), (1, 7), (1, 6), (2, 2), (2, 3), (2, 8), (2, 7)]
|
866 |
+
),
|
867 |
+
columns=["a"],
|
868 |
+
)
|
869 |
+
result = df.loc[(slice(None), indexer), :]
|
870 |
+
expected = DataFrame(
|
871 |
+
[1] * 8,
|
872 |
+
index=[[1, 1, 2, 1, 2, 1, 2, 2], [1, 2, 2, 7, 7, 6, 3, 8]],
|
873 |
+
columns=["a"],
|
874 |
+
)
|
875 |
+
tm.assert_frame_equal(result, expected)
|
876 |
+
|
877 |
+
result = df.loc[df.index.isin(indexer, level=1), :]
|
878 |
+
tm.assert_frame_equal(result, df)
|
879 |
+
|
880 |
+
|
881 |
+
def test_loc_getitem_drops_levels_for_one_row_dataframe():
|
882 |
+
# GH#10521 "x" and "z" are both scalar indexing, so those levels are dropped
|
883 |
+
mi = MultiIndex.from_arrays([["x"], ["y"], ["z"]], names=["a", "b", "c"])
|
884 |
+
df = DataFrame({"d": [0]}, index=mi)
|
885 |
+
expected = df.droplevel([0, 2])
|
886 |
+
result = df.loc["x", :, "z"]
|
887 |
+
tm.assert_frame_equal(result, expected)
|
888 |
+
|
889 |
+
ser = Series([0], index=mi)
|
890 |
+
result = ser.loc["x", :, "z"]
|
891 |
+
expected = Series([0], index=Index(["y"], name="b"))
|
892 |
+
tm.assert_series_equal(result, expected)
|
893 |
+
|
894 |
+
|
895 |
+
def test_mi_columns_loc_list_label_order():
|
896 |
+
# GH 10710
|
897 |
+
cols = MultiIndex.from_product([["A", "B", "C"], [1, 2]])
|
898 |
+
df = DataFrame(np.zeros((5, 6)), columns=cols)
|
899 |
+
result = df.loc[:, ["B", "A"]]
|
900 |
+
expected = DataFrame(
|
901 |
+
np.zeros((5, 4)),
|
902 |
+
columns=MultiIndex.from_tuples([("B", 1), ("B", 2), ("A", 1), ("A", 2)]),
|
903 |
+
)
|
904 |
+
tm.assert_frame_equal(result, expected)
|
905 |
+
|
906 |
+
|
907 |
+
def test_mi_partial_indexing_list_raises():
|
908 |
+
# GH 13501
|
909 |
+
frame = DataFrame(
|
910 |
+
np.arange(12).reshape((4, 3)),
|
911 |
+
index=[["a", "a", "b", "b"], [1, 2, 1, 2]],
|
912 |
+
columns=[["Ohio", "Ohio", "Colorado"], ["Green", "Red", "Green"]],
|
913 |
+
)
|
914 |
+
frame.index.names = ["key1", "key2"]
|
915 |
+
frame.columns.names = ["state", "color"]
|
916 |
+
with pytest.raises(KeyError, match="\\[2\\] not in index"):
|
917 |
+
frame.loc[["b", 2], "Colorado"]
|
918 |
+
|
919 |
+
|
920 |
+
def test_mi_indexing_list_nonexistent_raises():
|
921 |
+
# GH 15452
|
922 |
+
s = Series(range(4), index=MultiIndex.from_product([[1, 2], ["a", "b"]]))
|
923 |
+
with pytest.raises(KeyError, match="\\['not' 'found'\\] not in index"):
|
924 |
+
s.loc[["not", "found"]]
|
925 |
+
|
926 |
+
|
927 |
+
def test_mi_add_cell_missing_row_non_unique():
|
928 |
+
# GH 16018
|
929 |
+
result = DataFrame(
|
930 |
+
[[1, 2, 5, 6], [3, 4, 7, 8]],
|
931 |
+
index=["a", "a"],
|
932 |
+
columns=MultiIndex.from_product([[1, 2], ["A", "B"]]),
|
933 |
+
)
|
934 |
+
result.loc["c"] = -1
|
935 |
+
result.loc["c", (1, "A")] = 3
|
936 |
+
result.loc["d", (1, "A")] = 3
|
937 |
+
expected = DataFrame(
|
938 |
+
[
|
939 |
+
[1.0, 2.0, 5.0, 6.0],
|
940 |
+
[3.0, 4.0, 7.0, 8.0],
|
941 |
+
[3.0, -1.0, -1, -1],
|
942 |
+
[3.0, np.nan, np.nan, np.nan],
|
943 |
+
],
|
944 |
+
index=["a", "a", "c", "d"],
|
945 |
+
columns=MultiIndex.from_product([[1, 2], ["A", "B"]]),
|
946 |
+
)
|
947 |
+
tm.assert_frame_equal(result, expected)
|
948 |
+
|
949 |
+
|
950 |
+
def test_loc_get_scalar_casting_to_float():
|
951 |
+
# GH#41369
|
952 |
+
df = DataFrame(
|
953 |
+
{"a": 1.0, "b": 2}, index=MultiIndex.from_arrays([[3], [4]], names=["c", "d"])
|
954 |
+
)
|
955 |
+
result = df.loc[(3, 4), "b"]
|
956 |
+
assert result == 2
|
957 |
+
assert isinstance(result, np.int64)
|
958 |
+
result = df.loc[[(3, 4)], "b"].iloc[0]
|
959 |
+
assert result == 2
|
960 |
+
assert isinstance(result, np.int64)
|
961 |
+
|
962 |
+
|
963 |
+
def test_loc_empty_single_selector_with_names():
|
964 |
+
# GH 19517
|
965 |
+
idx = MultiIndex.from_product([["a", "b"], ["A", "B"]], names=[1, 0])
|
966 |
+
s2 = Series(index=idx, dtype=np.float64)
|
967 |
+
result = s2.loc["a"]
|
968 |
+
expected = Series([np.nan, np.nan], index=Index(["A", "B"], name=0))
|
969 |
+
tm.assert_series_equal(result, expected)
|
970 |
+
|
971 |
+
|
972 |
+
def test_loc_keyerror_rightmost_key_missing():
|
973 |
+
# GH 20951
|
974 |
+
|
975 |
+
df = DataFrame(
|
976 |
+
{
|
977 |
+
"A": [100, 100, 200, 200, 300, 300],
|
978 |
+
"B": [10, 10, 20, 21, 31, 33],
|
979 |
+
"C": range(6),
|
980 |
+
}
|
981 |
+
)
|
982 |
+
df = df.set_index(["A", "B"])
|
983 |
+
with pytest.raises(KeyError, match="^1$"):
|
984 |
+
df.loc[(100, 1)]
|
985 |
+
|
986 |
+
|
987 |
+
def test_multindex_series_loc_with_tuple_label():
|
988 |
+
# GH#43908
|
989 |
+
mi = MultiIndex.from_tuples([(1, 2), (3, (4, 5))])
|
990 |
+
ser = Series([1, 2], index=mi)
|
991 |
+
result = ser.loc[(3, (4, 5))]
|
992 |
+
assert result == 2
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_multiindex.py
ADDED
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
import pandas._libs.index as libindex
|
5 |
+
from pandas.errors import PerformanceWarning
|
6 |
+
|
7 |
+
import pandas as pd
|
8 |
+
from pandas import (
|
9 |
+
CategoricalDtype,
|
10 |
+
DataFrame,
|
11 |
+
Index,
|
12 |
+
MultiIndex,
|
13 |
+
Series,
|
14 |
+
)
|
15 |
+
import pandas._testing as tm
|
16 |
+
from pandas.core.arrays.boolean import BooleanDtype
|
17 |
+
|
18 |
+
|
19 |
+
class TestMultiIndexBasic:
|
20 |
+
def test_multiindex_perf_warn(self):
|
21 |
+
df = DataFrame(
|
22 |
+
{
|
23 |
+
"jim": [0, 0, 1, 1],
|
24 |
+
"joe": ["x", "x", "z", "y"],
|
25 |
+
"jolie": np.random.default_rng(2).random(4),
|
26 |
+
}
|
27 |
+
).set_index(["jim", "joe"])
|
28 |
+
|
29 |
+
with tm.assert_produces_warning(PerformanceWarning):
|
30 |
+
df.loc[(1, "z")]
|
31 |
+
|
32 |
+
df = df.iloc[[2, 1, 3, 0]]
|
33 |
+
with tm.assert_produces_warning(PerformanceWarning):
|
34 |
+
df.loc[(0,)]
|
35 |
+
|
36 |
+
@pytest.mark.parametrize("offset", [-5, 5])
|
37 |
+
def test_indexing_over_hashtable_size_cutoff(self, monkeypatch, offset):
|
38 |
+
size_cutoff = 20
|
39 |
+
n = size_cutoff + offset
|
40 |
+
|
41 |
+
with monkeypatch.context():
|
42 |
+
monkeypatch.setattr(libindex, "_SIZE_CUTOFF", size_cutoff)
|
43 |
+
s = Series(np.arange(n), MultiIndex.from_arrays((["a"] * n, np.arange(n))))
|
44 |
+
|
45 |
+
# hai it works!
|
46 |
+
assert s[("a", 5)] == 5
|
47 |
+
assert s[("a", 6)] == 6
|
48 |
+
assert s[("a", 7)] == 7
|
49 |
+
|
50 |
+
def test_multi_nan_indexing(self):
|
51 |
+
# GH 3588
|
52 |
+
df = DataFrame(
|
53 |
+
{
|
54 |
+
"a": ["R1", "R2", np.nan, "R4"],
|
55 |
+
"b": ["C1", "C2", "C3", "C4"],
|
56 |
+
"c": [10, 15, np.nan, 20],
|
57 |
+
}
|
58 |
+
)
|
59 |
+
result = df.set_index(["a", "b"], drop=False)
|
60 |
+
expected = DataFrame(
|
61 |
+
{
|
62 |
+
"a": ["R1", "R2", np.nan, "R4"],
|
63 |
+
"b": ["C1", "C2", "C3", "C4"],
|
64 |
+
"c": [10, 15, np.nan, 20],
|
65 |
+
},
|
66 |
+
index=[
|
67 |
+
Index(["R1", "R2", np.nan, "R4"], name="a"),
|
68 |
+
Index(["C1", "C2", "C3", "C4"], name="b"),
|
69 |
+
],
|
70 |
+
)
|
71 |
+
tm.assert_frame_equal(result, expected)
|
72 |
+
|
73 |
+
def test_exclusive_nat_column_indexing(self):
|
74 |
+
# GH 38025
|
75 |
+
# test multi indexing when one column exclusively contains NaT values
|
76 |
+
df = DataFrame(
|
77 |
+
{
|
78 |
+
"a": [pd.NaT, pd.NaT, pd.NaT, pd.NaT],
|
79 |
+
"b": ["C1", "C2", "C3", "C4"],
|
80 |
+
"c": [10, 15, np.nan, 20],
|
81 |
+
}
|
82 |
+
)
|
83 |
+
df = df.set_index(["a", "b"])
|
84 |
+
expected = DataFrame(
|
85 |
+
{
|
86 |
+
"c": [10, 15, np.nan, 20],
|
87 |
+
},
|
88 |
+
index=[
|
89 |
+
Index([pd.NaT, pd.NaT, pd.NaT, pd.NaT], name="a"),
|
90 |
+
Index(["C1", "C2", "C3", "C4"], name="b"),
|
91 |
+
],
|
92 |
+
)
|
93 |
+
tm.assert_frame_equal(df, expected)
|
94 |
+
|
95 |
+
def test_nested_tuples_duplicates(self):
|
96 |
+
# GH#30892
|
97 |
+
|
98 |
+
dti = pd.to_datetime(["20190101", "20190101", "20190102"])
|
99 |
+
idx = Index(["a", "a", "c"])
|
100 |
+
mi = MultiIndex.from_arrays([dti, idx], names=["index1", "index2"])
|
101 |
+
|
102 |
+
df = DataFrame({"c1": [1, 2, 3], "c2": [np.nan, np.nan, np.nan]}, index=mi)
|
103 |
+
|
104 |
+
expected = DataFrame({"c1": df["c1"], "c2": [1.0, 1.0, np.nan]}, index=mi)
|
105 |
+
|
106 |
+
df2 = df.copy(deep=True)
|
107 |
+
df2.loc[(dti[0], "a"), "c2"] = 1.0
|
108 |
+
tm.assert_frame_equal(df2, expected)
|
109 |
+
|
110 |
+
df3 = df.copy(deep=True)
|
111 |
+
df3.loc[[(dti[0], "a")], "c2"] = 1.0
|
112 |
+
tm.assert_frame_equal(df3, expected)
|
113 |
+
|
114 |
+
def test_multiindex_with_datatime_level_preserves_freq(self):
|
115 |
+
# https://github.com/pandas-dev/pandas/issues/35563
|
116 |
+
idx = Index(range(2), name="A")
|
117 |
+
dti = pd.date_range("2020-01-01", periods=7, freq="D", name="B")
|
118 |
+
mi = MultiIndex.from_product([idx, dti])
|
119 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((14, 2)), index=mi)
|
120 |
+
result = df.loc[0].index
|
121 |
+
tm.assert_index_equal(result, dti)
|
122 |
+
assert result.freq == dti.freq
|
123 |
+
|
124 |
+
def test_multiindex_complex(self):
|
125 |
+
# GH#42145
|
126 |
+
complex_data = [1 + 2j, 4 - 3j, 10 - 1j]
|
127 |
+
non_complex_data = [3, 4, 5]
|
128 |
+
result = DataFrame(
|
129 |
+
{
|
130 |
+
"x": complex_data,
|
131 |
+
"y": non_complex_data,
|
132 |
+
"z": non_complex_data,
|
133 |
+
}
|
134 |
+
)
|
135 |
+
result.set_index(["x", "y"], inplace=True)
|
136 |
+
expected = DataFrame(
|
137 |
+
{"z": non_complex_data},
|
138 |
+
index=MultiIndex.from_arrays(
|
139 |
+
[complex_data, non_complex_data],
|
140 |
+
names=("x", "y"),
|
141 |
+
),
|
142 |
+
)
|
143 |
+
tm.assert_frame_equal(result, expected)
|
144 |
+
|
145 |
+
def test_rename_multiindex_with_duplicates(self):
|
146 |
+
# GH 38015
|
147 |
+
mi = MultiIndex.from_tuples([("A", "cat"), ("B", "cat"), ("B", "cat")])
|
148 |
+
df = DataFrame(index=mi)
|
149 |
+
df = df.rename(index={"A": "Apple"}, level=0)
|
150 |
+
|
151 |
+
mi2 = MultiIndex.from_tuples([("Apple", "cat"), ("B", "cat"), ("B", "cat")])
|
152 |
+
expected = DataFrame(index=mi2)
|
153 |
+
tm.assert_frame_equal(df, expected)
|
154 |
+
|
155 |
+
def test_series_align_multiindex_with_nan_overlap_only(self):
|
156 |
+
# GH 38439
|
157 |
+
mi1 = MultiIndex.from_arrays([[81.0, np.nan], [np.nan, np.nan]])
|
158 |
+
mi2 = MultiIndex.from_arrays([[np.nan, 82.0], [np.nan, np.nan]])
|
159 |
+
ser1 = Series([1, 2], index=mi1)
|
160 |
+
ser2 = Series([1, 2], index=mi2)
|
161 |
+
result1, result2 = ser1.align(ser2)
|
162 |
+
|
163 |
+
mi = MultiIndex.from_arrays([[81.0, 82.0, np.nan], [np.nan, np.nan, np.nan]])
|
164 |
+
expected1 = Series([1.0, np.nan, 2.0], index=mi)
|
165 |
+
expected2 = Series([np.nan, 2.0, 1.0], index=mi)
|
166 |
+
|
167 |
+
tm.assert_series_equal(result1, expected1)
|
168 |
+
tm.assert_series_equal(result2, expected2)
|
169 |
+
|
170 |
+
def test_series_align_multiindex_with_nan(self):
|
171 |
+
# GH 38439
|
172 |
+
mi1 = MultiIndex.from_arrays([[81.0, np.nan], [np.nan, np.nan]])
|
173 |
+
mi2 = MultiIndex.from_arrays([[np.nan, 81.0], [np.nan, np.nan]])
|
174 |
+
ser1 = Series([1, 2], index=mi1)
|
175 |
+
ser2 = Series([1, 2], index=mi2)
|
176 |
+
result1, result2 = ser1.align(ser2)
|
177 |
+
|
178 |
+
mi = MultiIndex.from_arrays([[81.0, np.nan], [np.nan, np.nan]])
|
179 |
+
expected1 = Series([1, 2], index=mi)
|
180 |
+
expected2 = Series([2, 1], index=mi)
|
181 |
+
|
182 |
+
tm.assert_series_equal(result1, expected1)
|
183 |
+
tm.assert_series_equal(result2, expected2)
|
184 |
+
|
185 |
+
def test_nunique_smoke(self):
|
186 |
+
# GH 34019
|
187 |
+
n = DataFrame([[1, 2], [1, 2]]).set_index([0, 1]).index.nunique()
|
188 |
+
assert n == 1
|
189 |
+
|
190 |
+
def test_multiindex_repeated_keys(self):
|
191 |
+
# GH19414
|
192 |
+
tm.assert_series_equal(
|
193 |
+
Series([1, 2], MultiIndex.from_arrays([["a", "b"]])).loc[
|
194 |
+
["a", "a", "b", "b"]
|
195 |
+
],
|
196 |
+
Series([1, 1, 2, 2], MultiIndex.from_arrays([["a", "a", "b", "b"]])),
|
197 |
+
)
|
198 |
+
|
199 |
+
def test_multiindex_with_na_missing_key(self):
|
200 |
+
# GH46173
|
201 |
+
df = DataFrame.from_dict(
|
202 |
+
{
|
203 |
+
("foo",): [1, 2, 3],
|
204 |
+
("bar",): [5, 6, 7],
|
205 |
+
(None,): [8, 9, 0],
|
206 |
+
}
|
207 |
+
)
|
208 |
+
with pytest.raises(KeyError, match="missing_key"):
|
209 |
+
df[[("missing_key",)]]
|
210 |
+
|
211 |
+
def test_multiindex_dtype_preservation(self):
|
212 |
+
# GH51261
|
213 |
+
columns = MultiIndex.from_tuples([("A", "B")], names=["lvl1", "lvl2"])
|
214 |
+
df = DataFrame(["value"], columns=columns).astype("category")
|
215 |
+
df_no_multiindex = df["A"]
|
216 |
+
assert isinstance(df_no_multiindex["B"].dtype, CategoricalDtype)
|
217 |
+
|
218 |
+
# geopandas 1763 analogue
|
219 |
+
df = DataFrame(
|
220 |
+
[[1, 0], [0, 1]],
|
221 |
+
columns=[
|
222 |
+
["foo", "foo"],
|
223 |
+
["location", "location"],
|
224 |
+
["x", "y"],
|
225 |
+
],
|
226 |
+
).assign(bools=Series([True, False], dtype="boolean"))
|
227 |
+
assert isinstance(df["bools"].dtype, BooleanDtype)
|
228 |
+
|
229 |
+
def test_multiindex_from_tuples_with_nan(self):
|
230 |
+
# GH#23578
|
231 |
+
result = MultiIndex.from_tuples([("a", "b", "c"), np.nan, ("d", "", "")])
|
232 |
+
expected = MultiIndex.from_tuples(
|
233 |
+
[("a", "b", "c"), (np.nan, np.nan, np.nan), ("d", "", "")]
|
234 |
+
)
|
235 |
+
tm.assert_index_equal(result, expected)
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_partial.py
ADDED
@@ -0,0 +1,269 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
import pandas.util._test_decorators as td
|
5 |
+
|
6 |
+
from pandas import (
|
7 |
+
DataFrame,
|
8 |
+
DatetimeIndex,
|
9 |
+
MultiIndex,
|
10 |
+
date_range,
|
11 |
+
)
|
12 |
+
import pandas._testing as tm
|
13 |
+
|
14 |
+
|
15 |
+
class TestMultiIndexPartial:
|
16 |
+
def test_getitem_partial_int(self):
|
17 |
+
# GH 12416
|
18 |
+
# with single item
|
19 |
+
l1 = [10, 20]
|
20 |
+
l2 = ["a", "b"]
|
21 |
+
df = DataFrame(index=range(2), columns=MultiIndex.from_product([l1, l2]))
|
22 |
+
expected = DataFrame(index=range(2), columns=l2)
|
23 |
+
result = df[20]
|
24 |
+
tm.assert_frame_equal(result, expected)
|
25 |
+
|
26 |
+
# with list
|
27 |
+
expected = DataFrame(
|
28 |
+
index=range(2), columns=MultiIndex.from_product([l1[1:], l2])
|
29 |
+
)
|
30 |
+
result = df[[20]]
|
31 |
+
tm.assert_frame_equal(result, expected)
|
32 |
+
|
33 |
+
# missing item:
|
34 |
+
with pytest.raises(KeyError, match="1"):
|
35 |
+
df[1]
|
36 |
+
with pytest.raises(KeyError, match=r"'\[1\] not in index'"):
|
37 |
+
df[[1]]
|
38 |
+
|
39 |
+
def test_series_slice_partial(self):
|
40 |
+
pass
|
41 |
+
|
42 |
+
def test_xs_partial(
|
43 |
+
self,
|
44 |
+
multiindex_dataframe_random_data,
|
45 |
+
multiindex_year_month_day_dataframe_random_data,
|
46 |
+
):
|
47 |
+
frame = multiindex_dataframe_random_data
|
48 |
+
ymd = multiindex_year_month_day_dataframe_random_data
|
49 |
+
result = frame.xs("foo")
|
50 |
+
result2 = frame.loc["foo"]
|
51 |
+
expected = frame.T["foo"].T
|
52 |
+
tm.assert_frame_equal(result, expected)
|
53 |
+
tm.assert_frame_equal(result, result2)
|
54 |
+
|
55 |
+
result = ymd.xs((2000, 4))
|
56 |
+
expected = ymd.loc[2000, 4]
|
57 |
+
tm.assert_frame_equal(result, expected)
|
58 |
+
|
59 |
+
# ex from #1796
|
60 |
+
index = MultiIndex(
|
61 |
+
levels=[["foo", "bar"], ["one", "two"], [-1, 1]],
|
62 |
+
codes=[
|
63 |
+
[0, 0, 0, 0, 1, 1, 1, 1],
|
64 |
+
[0, 0, 1, 1, 0, 0, 1, 1],
|
65 |
+
[0, 1, 0, 1, 0, 1, 0, 1],
|
66 |
+
],
|
67 |
+
)
|
68 |
+
df = DataFrame(
|
69 |
+
np.random.default_rng(2).standard_normal((8, 4)),
|
70 |
+
index=index,
|
71 |
+
columns=list("abcd"),
|
72 |
+
)
|
73 |
+
|
74 |
+
result = df.xs(("foo", "one"))
|
75 |
+
expected = df.loc["foo", "one"]
|
76 |
+
tm.assert_frame_equal(result, expected)
|
77 |
+
|
78 |
+
def test_getitem_partial(self, multiindex_year_month_day_dataframe_random_data):
|
79 |
+
ymd = multiindex_year_month_day_dataframe_random_data
|
80 |
+
ymd = ymd.T
|
81 |
+
result = ymd[2000, 2]
|
82 |
+
|
83 |
+
expected = ymd.reindex(columns=ymd.columns[ymd.columns.codes[1] == 1])
|
84 |
+
expected.columns = expected.columns.droplevel(0).droplevel(0)
|
85 |
+
tm.assert_frame_equal(result, expected)
|
86 |
+
|
87 |
+
def test_fancy_slice_partial(
|
88 |
+
self,
|
89 |
+
multiindex_dataframe_random_data,
|
90 |
+
multiindex_year_month_day_dataframe_random_data,
|
91 |
+
):
|
92 |
+
frame = multiindex_dataframe_random_data
|
93 |
+
result = frame.loc["bar":"baz"]
|
94 |
+
expected = frame[3:7]
|
95 |
+
tm.assert_frame_equal(result, expected)
|
96 |
+
|
97 |
+
ymd = multiindex_year_month_day_dataframe_random_data
|
98 |
+
result = ymd.loc[(2000, 2):(2000, 4)]
|
99 |
+
lev = ymd.index.codes[1]
|
100 |
+
expected = ymd[(lev >= 1) & (lev <= 3)]
|
101 |
+
tm.assert_frame_equal(result, expected)
|
102 |
+
|
103 |
+
def test_getitem_partial_column_select(self):
|
104 |
+
idx = MultiIndex(
|
105 |
+
codes=[[0, 0, 0], [0, 1, 1], [1, 0, 1]],
|
106 |
+
levels=[["a", "b"], ["x", "y"], ["p", "q"]],
|
107 |
+
)
|
108 |
+
df = DataFrame(np.random.default_rng(2).random((3, 2)), index=idx)
|
109 |
+
|
110 |
+
result = df.loc[("a", "y"), :]
|
111 |
+
expected = df.loc[("a", "y")]
|
112 |
+
tm.assert_frame_equal(result, expected)
|
113 |
+
|
114 |
+
result = df.loc[("a", "y"), [1, 0]]
|
115 |
+
expected = df.loc[("a", "y")][[1, 0]]
|
116 |
+
tm.assert_frame_equal(result, expected)
|
117 |
+
|
118 |
+
with pytest.raises(KeyError, match=r"\('a', 'foo'\)"):
|
119 |
+
df.loc[("a", "foo"), :]
|
120 |
+
|
121 |
+
# TODO(ArrayManager) rewrite test to not use .values
|
122 |
+
# exp.loc[2000, 4].values[:] select multiple columns -> .values is not a view
|
123 |
+
@td.skip_array_manager_invalid_test
|
124 |
+
def test_partial_set(
|
125 |
+
self,
|
126 |
+
multiindex_year_month_day_dataframe_random_data,
|
127 |
+
using_copy_on_write,
|
128 |
+
warn_copy_on_write,
|
129 |
+
):
|
130 |
+
# GH #397
|
131 |
+
ymd = multiindex_year_month_day_dataframe_random_data
|
132 |
+
df = ymd.copy()
|
133 |
+
exp = ymd.copy()
|
134 |
+
df.loc[2000, 4] = 0
|
135 |
+
exp.iloc[65:85] = 0
|
136 |
+
tm.assert_frame_equal(df, exp)
|
137 |
+
|
138 |
+
if using_copy_on_write:
|
139 |
+
with tm.raises_chained_assignment_error():
|
140 |
+
df["A"].loc[2000, 4] = 1
|
141 |
+
df.loc[(2000, 4), "A"] = 1
|
142 |
+
else:
|
143 |
+
with tm.raises_chained_assignment_error():
|
144 |
+
df["A"].loc[2000, 4] = 1
|
145 |
+
exp.iloc[65:85, 0] = 1
|
146 |
+
tm.assert_frame_equal(df, exp)
|
147 |
+
|
148 |
+
df.loc[2000] = 5
|
149 |
+
exp.iloc[:100] = 5
|
150 |
+
tm.assert_frame_equal(df, exp)
|
151 |
+
|
152 |
+
# this works...for now
|
153 |
+
with tm.raises_chained_assignment_error():
|
154 |
+
df["A"].iloc[14] = 5
|
155 |
+
if using_copy_on_write:
|
156 |
+
assert df["A"].iloc[14] == exp["A"].iloc[14]
|
157 |
+
else:
|
158 |
+
assert df["A"].iloc[14] == 5
|
159 |
+
|
160 |
+
@pytest.mark.parametrize("dtype", [int, float])
|
161 |
+
def test_getitem_intkey_leading_level(
|
162 |
+
self, multiindex_year_month_day_dataframe_random_data, dtype
|
163 |
+
):
|
164 |
+
# GH#33355 dont fall-back to positional when leading level is int
|
165 |
+
ymd = multiindex_year_month_day_dataframe_random_data
|
166 |
+
levels = ymd.index.levels
|
167 |
+
ymd.index = ymd.index.set_levels([levels[0].astype(dtype)] + levels[1:])
|
168 |
+
ser = ymd["A"]
|
169 |
+
mi = ser.index
|
170 |
+
assert isinstance(mi, MultiIndex)
|
171 |
+
if dtype is int:
|
172 |
+
assert mi.levels[0].dtype == np.dtype(int)
|
173 |
+
else:
|
174 |
+
assert mi.levels[0].dtype == np.float64
|
175 |
+
|
176 |
+
assert 14 not in mi.levels[0]
|
177 |
+
assert not mi.levels[0]._should_fallback_to_positional
|
178 |
+
assert not mi._should_fallback_to_positional
|
179 |
+
|
180 |
+
with pytest.raises(KeyError, match="14"):
|
181 |
+
ser[14]
|
182 |
+
|
183 |
+
# ---------------------------------------------------------------------
|
184 |
+
|
185 |
+
def test_setitem_multiple_partial(self, multiindex_dataframe_random_data):
|
186 |
+
frame = multiindex_dataframe_random_data
|
187 |
+
expected = frame.copy()
|
188 |
+
result = frame.copy()
|
189 |
+
result.loc[["foo", "bar"]] = 0
|
190 |
+
expected.loc["foo"] = 0
|
191 |
+
expected.loc["bar"] = 0
|
192 |
+
tm.assert_frame_equal(result, expected)
|
193 |
+
|
194 |
+
expected = frame.copy()
|
195 |
+
result = frame.copy()
|
196 |
+
result.loc["foo":"bar"] = 0
|
197 |
+
expected.loc["foo"] = 0
|
198 |
+
expected.loc["bar"] = 0
|
199 |
+
tm.assert_frame_equal(result, expected)
|
200 |
+
|
201 |
+
expected = frame["A"].copy()
|
202 |
+
result = frame["A"].copy()
|
203 |
+
result.loc[["foo", "bar"]] = 0
|
204 |
+
expected.loc["foo"] = 0
|
205 |
+
expected.loc["bar"] = 0
|
206 |
+
tm.assert_series_equal(result, expected)
|
207 |
+
|
208 |
+
expected = frame["A"].copy()
|
209 |
+
result = frame["A"].copy()
|
210 |
+
result.loc["foo":"bar"] = 0
|
211 |
+
expected.loc["foo"] = 0
|
212 |
+
expected.loc["bar"] = 0
|
213 |
+
tm.assert_series_equal(result, expected)
|
214 |
+
|
215 |
+
@pytest.mark.parametrize(
|
216 |
+
"indexer, exp_idx, exp_values",
|
217 |
+
[
|
218 |
+
(
|
219 |
+
slice("2019-2", None),
|
220 |
+
DatetimeIndex(["2019-02-01"], dtype="M8[ns]"),
|
221 |
+
[2, 3],
|
222 |
+
),
|
223 |
+
(
|
224 |
+
slice(None, "2019-2"),
|
225 |
+
date_range("2019", periods=2, freq="MS"),
|
226 |
+
[0, 1, 2, 3],
|
227 |
+
),
|
228 |
+
],
|
229 |
+
)
|
230 |
+
def test_partial_getitem_loc_datetime(self, indexer, exp_idx, exp_values):
|
231 |
+
# GH: 25165
|
232 |
+
date_idx = date_range("2019", periods=2, freq="MS")
|
233 |
+
df = DataFrame(
|
234 |
+
list(range(4)),
|
235 |
+
index=MultiIndex.from_product([date_idx, [0, 1]], names=["x", "y"]),
|
236 |
+
)
|
237 |
+
expected = DataFrame(
|
238 |
+
exp_values,
|
239 |
+
index=MultiIndex.from_product([exp_idx, [0, 1]], names=["x", "y"]),
|
240 |
+
)
|
241 |
+
result = df[indexer]
|
242 |
+
tm.assert_frame_equal(result, expected)
|
243 |
+
result = df.loc[indexer]
|
244 |
+
tm.assert_frame_equal(result, expected)
|
245 |
+
|
246 |
+
result = df.loc(axis=0)[indexer]
|
247 |
+
tm.assert_frame_equal(result, expected)
|
248 |
+
|
249 |
+
result = df.loc[indexer, :]
|
250 |
+
tm.assert_frame_equal(result, expected)
|
251 |
+
|
252 |
+
df2 = df.swaplevel(0, 1).sort_index()
|
253 |
+
expected = expected.swaplevel(0, 1).sort_index()
|
254 |
+
|
255 |
+
result = df2.loc[:, indexer, :]
|
256 |
+
tm.assert_frame_equal(result, expected)
|
257 |
+
|
258 |
+
|
259 |
+
def test_loc_getitem_partial_both_axis():
|
260 |
+
# gh-12660
|
261 |
+
iterables = [["a", "b"], [2, 1]]
|
262 |
+
columns = MultiIndex.from_product(iterables, names=["col1", "col2"])
|
263 |
+
rows = MultiIndex.from_product(iterables, names=["row1", "row2"])
|
264 |
+
df = DataFrame(
|
265 |
+
np.random.default_rng(2).standard_normal((4, 4)), index=rows, columns=columns
|
266 |
+
)
|
267 |
+
expected = df.iloc[:2, 2:].droplevel("row1").droplevel("col1", axis=1)
|
268 |
+
result = df.loc["a", "b"]
|
269 |
+
tm.assert_frame_equal(result, expected)
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_setitem.py
ADDED
@@ -0,0 +1,589 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas.errors import SettingWithCopyError
|
5 |
+
import pandas.util._test_decorators as td
|
6 |
+
|
7 |
+
import pandas as pd
|
8 |
+
from pandas import (
|
9 |
+
DataFrame,
|
10 |
+
MultiIndex,
|
11 |
+
Series,
|
12 |
+
date_range,
|
13 |
+
isna,
|
14 |
+
notna,
|
15 |
+
)
|
16 |
+
import pandas._testing as tm
|
17 |
+
|
18 |
+
|
19 |
+
def assert_equal(a, b):
|
20 |
+
assert a == b
|
21 |
+
|
22 |
+
|
23 |
+
class TestMultiIndexSetItem:
|
24 |
+
def check(self, target, indexers, value, compare_fn=assert_equal, expected=None):
|
25 |
+
target.loc[indexers] = value
|
26 |
+
result = target.loc[indexers]
|
27 |
+
if expected is None:
|
28 |
+
expected = value
|
29 |
+
compare_fn(result, expected)
|
30 |
+
|
31 |
+
def test_setitem_multiindex(self):
|
32 |
+
# GH#7190
|
33 |
+
cols = ["A", "w", "l", "a", "x", "X", "d", "profit"]
|
34 |
+
index = MultiIndex.from_product(
|
35 |
+
[np.arange(0, 100), np.arange(0, 80)], names=["time", "firm"]
|
36 |
+
)
|
37 |
+
t, n = 0, 2
|
38 |
+
|
39 |
+
df = DataFrame(
|
40 |
+
np.nan,
|
41 |
+
columns=cols,
|
42 |
+
index=index,
|
43 |
+
)
|
44 |
+
self.check(target=df, indexers=((t, n), "X"), value=0)
|
45 |
+
|
46 |
+
df = DataFrame(-999, columns=cols, index=index)
|
47 |
+
self.check(target=df, indexers=((t, n), "X"), value=1)
|
48 |
+
|
49 |
+
df = DataFrame(columns=cols, index=index)
|
50 |
+
self.check(target=df, indexers=((t, n), "X"), value=2)
|
51 |
+
|
52 |
+
# gh-7218: assigning with 0-dim arrays
|
53 |
+
df = DataFrame(-999, columns=cols, index=index)
|
54 |
+
self.check(
|
55 |
+
target=df,
|
56 |
+
indexers=((t, n), "X"),
|
57 |
+
value=np.array(3),
|
58 |
+
expected=3,
|
59 |
+
)
|
60 |
+
|
61 |
+
def test_setitem_multiindex2(self):
|
62 |
+
# GH#5206
|
63 |
+
df = DataFrame(
|
64 |
+
np.arange(25).reshape(5, 5), columns="A,B,C,D,E".split(","), dtype=float
|
65 |
+
)
|
66 |
+
df["F"] = 99
|
67 |
+
row_selection = df["A"] % 2 == 0
|
68 |
+
col_selection = ["B", "C"]
|
69 |
+
df.loc[row_selection, col_selection] = df["F"]
|
70 |
+
output = DataFrame(99.0, index=[0, 2, 4], columns=["B", "C"])
|
71 |
+
tm.assert_frame_equal(df.loc[row_selection, col_selection], output)
|
72 |
+
self.check(
|
73 |
+
target=df,
|
74 |
+
indexers=(row_selection, col_selection),
|
75 |
+
value=df["F"],
|
76 |
+
compare_fn=tm.assert_frame_equal,
|
77 |
+
expected=output,
|
78 |
+
)
|
79 |
+
|
80 |
+
def test_setitem_multiindex3(self):
|
81 |
+
# GH#11372
|
82 |
+
idx = MultiIndex.from_product(
|
83 |
+
[["A", "B", "C"], date_range("2015-01-01", "2015-04-01", freq="MS")]
|
84 |
+
)
|
85 |
+
cols = MultiIndex.from_product(
|
86 |
+
[["foo", "bar"], date_range("2016-01-01", "2016-02-01", freq="MS")]
|
87 |
+
)
|
88 |
+
|
89 |
+
df = DataFrame(
|
90 |
+
np.random.default_rng(2).random((12, 4)), index=idx, columns=cols
|
91 |
+
)
|
92 |
+
|
93 |
+
subidx = MultiIndex.from_arrays(
|
94 |
+
[["A", "A"], date_range("2015-01-01", "2015-02-01", freq="MS")]
|
95 |
+
)
|
96 |
+
subcols = MultiIndex.from_arrays(
|
97 |
+
[["foo", "foo"], date_range("2016-01-01", "2016-02-01", freq="MS")]
|
98 |
+
)
|
99 |
+
|
100 |
+
vals = DataFrame(
|
101 |
+
np.random.default_rng(2).random((2, 2)), index=subidx, columns=subcols
|
102 |
+
)
|
103 |
+
self.check(
|
104 |
+
target=df,
|
105 |
+
indexers=(subidx, subcols),
|
106 |
+
value=vals,
|
107 |
+
compare_fn=tm.assert_frame_equal,
|
108 |
+
)
|
109 |
+
# set all columns
|
110 |
+
vals = DataFrame(
|
111 |
+
np.random.default_rng(2).random((2, 4)), index=subidx, columns=cols
|
112 |
+
)
|
113 |
+
self.check(
|
114 |
+
target=df,
|
115 |
+
indexers=(subidx, slice(None, None, None)),
|
116 |
+
value=vals,
|
117 |
+
compare_fn=tm.assert_frame_equal,
|
118 |
+
)
|
119 |
+
# identity
|
120 |
+
copy = df.copy()
|
121 |
+
self.check(
|
122 |
+
target=df,
|
123 |
+
indexers=(df.index, df.columns),
|
124 |
+
value=df,
|
125 |
+
compare_fn=tm.assert_frame_equal,
|
126 |
+
expected=copy,
|
127 |
+
)
|
128 |
+
|
129 |
+
# TODO(ArrayManager) df.loc["bar"] *= 2 doesn't raise an error but results in
|
130 |
+
# all NaNs -> doesn't work in the "split" path (also for BlockManager actually)
|
131 |
+
@td.skip_array_manager_not_yet_implemented
|
132 |
+
def test_multiindex_setitem(self):
|
133 |
+
# GH 3738
|
134 |
+
# setting with a multi-index right hand side
|
135 |
+
arrays = [
|
136 |
+
np.array(["bar", "bar", "baz", "qux", "qux", "bar"]),
|
137 |
+
np.array(["one", "two", "one", "one", "two", "one"]),
|
138 |
+
np.arange(0, 6, 1),
|
139 |
+
]
|
140 |
+
|
141 |
+
df_orig = DataFrame(
|
142 |
+
np.random.default_rng(2).standard_normal((6, 3)),
|
143 |
+
index=arrays,
|
144 |
+
columns=["A", "B", "C"],
|
145 |
+
).sort_index()
|
146 |
+
|
147 |
+
expected = df_orig.loc[["bar"]] * 2
|
148 |
+
df = df_orig.copy()
|
149 |
+
df.loc[["bar"]] *= 2
|
150 |
+
tm.assert_frame_equal(df.loc[["bar"]], expected)
|
151 |
+
|
152 |
+
# raise because these have differing levels
|
153 |
+
msg = "cannot align on a multi-index with out specifying the join levels"
|
154 |
+
with pytest.raises(TypeError, match=msg):
|
155 |
+
df.loc["bar"] *= 2
|
156 |
+
|
157 |
+
def test_multiindex_setitem2(self):
|
158 |
+
# from SO
|
159 |
+
# https://stackoverflow.com/questions/24572040/pandas-access-the-level-of-multiindex-for-inplace-operation
|
160 |
+
df_orig = DataFrame.from_dict(
|
161 |
+
{
|
162 |
+
"price": {
|
163 |
+
("DE", "Coal", "Stock"): 2,
|
164 |
+
("DE", "Gas", "Stock"): 4,
|
165 |
+
("DE", "Elec", "Demand"): 1,
|
166 |
+
("FR", "Gas", "Stock"): 5,
|
167 |
+
("FR", "Solar", "SupIm"): 0,
|
168 |
+
("FR", "Wind", "SupIm"): 0,
|
169 |
+
}
|
170 |
+
}
|
171 |
+
)
|
172 |
+
df_orig.index = MultiIndex.from_tuples(
|
173 |
+
df_orig.index, names=["Sit", "Com", "Type"]
|
174 |
+
)
|
175 |
+
|
176 |
+
expected = df_orig.copy()
|
177 |
+
expected.iloc[[0, 1, 3]] *= 2
|
178 |
+
|
179 |
+
idx = pd.IndexSlice
|
180 |
+
df = df_orig.copy()
|
181 |
+
df.loc[idx[:, :, "Stock"], :] *= 2
|
182 |
+
tm.assert_frame_equal(df, expected)
|
183 |
+
|
184 |
+
df = df_orig.copy()
|
185 |
+
df.loc[idx[:, :, "Stock"], "price"] *= 2
|
186 |
+
tm.assert_frame_equal(df, expected)
|
187 |
+
|
188 |
+
def test_multiindex_assignment(self):
|
189 |
+
# GH3777 part 2
|
190 |
+
|
191 |
+
# mixed dtype
|
192 |
+
df = DataFrame(
|
193 |
+
np.random.default_rng(2).integers(5, 10, size=9).reshape(3, 3),
|
194 |
+
columns=list("abc"),
|
195 |
+
index=[[4, 4, 8], [8, 10, 12]],
|
196 |
+
)
|
197 |
+
df["d"] = np.nan
|
198 |
+
arr = np.array([0.0, 1.0])
|
199 |
+
|
200 |
+
df.loc[4, "d"] = arr
|
201 |
+
tm.assert_series_equal(df.loc[4, "d"], Series(arr, index=[8, 10], name="d"))
|
202 |
+
|
203 |
+
def test_multiindex_assignment_single_dtype(
|
204 |
+
self, using_copy_on_write, warn_copy_on_write
|
205 |
+
):
|
206 |
+
# GH3777 part 2b
|
207 |
+
# single dtype
|
208 |
+
arr = np.array([0.0, 1.0])
|
209 |
+
|
210 |
+
df = DataFrame(
|
211 |
+
np.random.default_rng(2).integers(5, 10, size=9).reshape(3, 3),
|
212 |
+
columns=list("abc"),
|
213 |
+
index=[[4, 4, 8], [8, 10, 12]],
|
214 |
+
dtype=np.int64,
|
215 |
+
)
|
216 |
+
view = df["c"].iloc[:2].values
|
217 |
+
|
218 |
+
# arr can be losslessly cast to int, so this setitem is inplace
|
219 |
+
# INFO(CoW-warn) this does not warn because we directly took .values
|
220 |
+
# above, so no reference to a pandas object is alive for `view`
|
221 |
+
df.loc[4, "c"] = arr
|
222 |
+
exp = Series(arr, index=[8, 10], name="c", dtype="int64")
|
223 |
+
result = df.loc[4, "c"]
|
224 |
+
tm.assert_series_equal(result, exp)
|
225 |
+
|
226 |
+
# extra check for inplace-ness
|
227 |
+
if not using_copy_on_write:
|
228 |
+
tm.assert_numpy_array_equal(view, exp.values)
|
229 |
+
|
230 |
+
# arr + 0.5 cannot be cast losslessly to int, so we upcast
|
231 |
+
with tm.assert_produces_warning(
|
232 |
+
FutureWarning, match="item of incompatible dtype"
|
233 |
+
):
|
234 |
+
df.loc[4, "c"] = arr + 0.5
|
235 |
+
result = df.loc[4, "c"]
|
236 |
+
exp = exp + 0.5
|
237 |
+
tm.assert_series_equal(result, exp)
|
238 |
+
|
239 |
+
# scalar ok
|
240 |
+
with tm.assert_cow_warning(warn_copy_on_write):
|
241 |
+
df.loc[4, "c"] = 10
|
242 |
+
exp = Series(10, index=[8, 10], name="c", dtype="float64")
|
243 |
+
tm.assert_series_equal(df.loc[4, "c"], exp)
|
244 |
+
|
245 |
+
# invalid assignments
|
246 |
+
msg = "Must have equal len keys and value when setting with an iterable"
|
247 |
+
with pytest.raises(ValueError, match=msg):
|
248 |
+
df.loc[4, "c"] = [0, 1, 2, 3]
|
249 |
+
|
250 |
+
with pytest.raises(ValueError, match=msg):
|
251 |
+
df.loc[4, "c"] = [0]
|
252 |
+
|
253 |
+
# But with a length-1 listlike column indexer this behaves like
|
254 |
+
# `df.loc[4, "c"] = 0
|
255 |
+
with tm.assert_cow_warning(warn_copy_on_write):
|
256 |
+
df.loc[4, ["c"]] = [0]
|
257 |
+
assert (df.loc[4, "c"] == 0).all()
|
258 |
+
|
259 |
+
def test_groupby_example(self):
|
260 |
+
# groupby example
|
261 |
+
NUM_ROWS = 100
|
262 |
+
NUM_COLS = 10
|
263 |
+
col_names = ["A" + num for num in map(str, np.arange(NUM_COLS).tolist())]
|
264 |
+
index_cols = col_names[:5]
|
265 |
+
|
266 |
+
df = DataFrame(
|
267 |
+
np.random.default_rng(2).integers(5, size=(NUM_ROWS, NUM_COLS)),
|
268 |
+
dtype=np.int64,
|
269 |
+
columns=col_names,
|
270 |
+
)
|
271 |
+
df = df.set_index(index_cols).sort_index()
|
272 |
+
grp = df.groupby(level=index_cols[:4])
|
273 |
+
df["new_col"] = np.nan
|
274 |
+
|
275 |
+
# we are actually operating on a copy here
|
276 |
+
# but in this case, that's ok
|
277 |
+
for name, df2 in grp:
|
278 |
+
new_vals = np.arange(df2.shape[0])
|
279 |
+
df.loc[name, "new_col"] = new_vals
|
280 |
+
|
281 |
+
def test_series_setitem(
|
282 |
+
self, multiindex_year_month_day_dataframe_random_data, warn_copy_on_write
|
283 |
+
):
|
284 |
+
ymd = multiindex_year_month_day_dataframe_random_data
|
285 |
+
s = ymd["A"]
|
286 |
+
|
287 |
+
with tm.assert_cow_warning(warn_copy_on_write):
|
288 |
+
s[2000, 3] = np.nan
|
289 |
+
assert isna(s.values[42:65]).all()
|
290 |
+
assert notna(s.values[:42]).all()
|
291 |
+
assert notna(s.values[65:]).all()
|
292 |
+
|
293 |
+
with tm.assert_cow_warning(warn_copy_on_write):
|
294 |
+
s[2000, 3, 10] = np.nan
|
295 |
+
assert isna(s.iloc[49])
|
296 |
+
|
297 |
+
with pytest.raises(KeyError, match="49"):
|
298 |
+
# GH#33355 dont fall-back to positional when leading level is int
|
299 |
+
s[49]
|
300 |
+
|
301 |
+
def test_frame_getitem_setitem_boolean(self, multiindex_dataframe_random_data):
|
302 |
+
frame = multiindex_dataframe_random_data
|
303 |
+
df = frame.T.copy()
|
304 |
+
values = df.values.copy()
|
305 |
+
|
306 |
+
result = df[df > 0]
|
307 |
+
expected = df.where(df > 0)
|
308 |
+
tm.assert_frame_equal(result, expected)
|
309 |
+
|
310 |
+
df[df > 0] = 5
|
311 |
+
values[values > 0] = 5
|
312 |
+
tm.assert_almost_equal(df.values, values)
|
313 |
+
|
314 |
+
df[df == 5] = 0
|
315 |
+
values[values == 5] = 0
|
316 |
+
tm.assert_almost_equal(df.values, values)
|
317 |
+
|
318 |
+
# a df that needs alignment first
|
319 |
+
df[df[:-1] < 0] = 2
|
320 |
+
np.putmask(values[:-1], values[:-1] < 0, 2)
|
321 |
+
tm.assert_almost_equal(df.values, values)
|
322 |
+
|
323 |
+
with pytest.raises(TypeError, match="boolean values only"):
|
324 |
+
df[df * 0] = 2
|
325 |
+
|
326 |
+
def test_frame_getitem_setitem_multislice(self):
|
327 |
+
levels = [["t1", "t2"], ["a", "b", "c"]]
|
328 |
+
codes = [[0, 0, 0, 1, 1], [0, 1, 2, 0, 1]]
|
329 |
+
midx = MultiIndex(codes=codes, levels=levels, names=[None, "id"])
|
330 |
+
df = DataFrame({"value": [1, 2, 3, 7, 8]}, index=midx)
|
331 |
+
|
332 |
+
result = df.loc[:, "value"]
|
333 |
+
tm.assert_series_equal(df["value"], result)
|
334 |
+
|
335 |
+
result = df.loc[df.index[1:3], "value"]
|
336 |
+
tm.assert_series_equal(df["value"][1:3], result)
|
337 |
+
|
338 |
+
result = df.loc[:, :]
|
339 |
+
tm.assert_frame_equal(df, result)
|
340 |
+
|
341 |
+
result = df
|
342 |
+
df.loc[:, "value"] = 10
|
343 |
+
result["value"] = 10
|
344 |
+
tm.assert_frame_equal(df, result)
|
345 |
+
|
346 |
+
df.loc[:, :] = 10
|
347 |
+
tm.assert_frame_equal(df, result)
|
348 |
+
|
349 |
+
def test_frame_setitem_multi_column(self):
|
350 |
+
df = DataFrame(
|
351 |
+
np.random.default_rng(2).standard_normal((10, 4)),
|
352 |
+
columns=[["a", "a", "b", "b"], [0, 1, 0, 1]],
|
353 |
+
)
|
354 |
+
|
355 |
+
cp = df.copy()
|
356 |
+
cp["a"] = cp["b"]
|
357 |
+
tm.assert_frame_equal(cp["a"], cp["b"])
|
358 |
+
|
359 |
+
# set with ndarray
|
360 |
+
cp = df.copy()
|
361 |
+
cp["a"] = cp["b"].values
|
362 |
+
tm.assert_frame_equal(cp["a"], cp["b"])
|
363 |
+
|
364 |
+
def test_frame_setitem_multi_column2(self):
|
365 |
+
# ---------------------------------------
|
366 |
+
# GH#1803
|
367 |
+
columns = MultiIndex.from_tuples([("A", "1"), ("A", "2"), ("B", "1")])
|
368 |
+
df = DataFrame(index=[1, 3, 5], columns=columns)
|
369 |
+
|
370 |
+
# Works, but adds a column instead of updating the two existing ones
|
371 |
+
df["A"] = 0.0 # Doesn't work
|
372 |
+
assert (df["A"].values == 0).all()
|
373 |
+
|
374 |
+
# it broadcasts
|
375 |
+
df["B", "1"] = [1, 2, 3]
|
376 |
+
df["A"] = df["B", "1"]
|
377 |
+
|
378 |
+
sliced_a1 = df["A", "1"]
|
379 |
+
sliced_a2 = df["A", "2"]
|
380 |
+
sliced_b1 = df["B", "1"]
|
381 |
+
tm.assert_series_equal(sliced_a1, sliced_b1, check_names=False)
|
382 |
+
tm.assert_series_equal(sliced_a2, sliced_b1, check_names=False)
|
383 |
+
assert sliced_a1.name == ("A", "1")
|
384 |
+
assert sliced_a2.name == ("A", "2")
|
385 |
+
assert sliced_b1.name == ("B", "1")
|
386 |
+
|
387 |
+
def test_loc_getitem_tuple_plus_columns(
|
388 |
+
self, multiindex_year_month_day_dataframe_random_data
|
389 |
+
):
|
390 |
+
# GH #1013
|
391 |
+
ymd = multiindex_year_month_day_dataframe_random_data
|
392 |
+
df = ymd[:5]
|
393 |
+
|
394 |
+
result = df.loc[(2000, 1, 6), ["A", "B", "C"]]
|
395 |
+
expected = df.loc[2000, 1, 6][["A", "B", "C"]]
|
396 |
+
tm.assert_series_equal(result, expected)
|
397 |
+
|
398 |
+
@pytest.mark.filterwarnings("ignore:Setting a value on a view:FutureWarning")
|
399 |
+
def test_loc_getitem_setitem_slice_integers(self, frame_or_series):
|
400 |
+
index = MultiIndex(
|
401 |
+
levels=[[0, 1, 2], [0, 2]], codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]]
|
402 |
+
)
|
403 |
+
|
404 |
+
obj = DataFrame(
|
405 |
+
np.random.default_rng(2).standard_normal((len(index), 4)),
|
406 |
+
index=index,
|
407 |
+
columns=["a", "b", "c", "d"],
|
408 |
+
)
|
409 |
+
obj = tm.get_obj(obj, frame_or_series)
|
410 |
+
|
411 |
+
res = obj.loc[1:2]
|
412 |
+
exp = obj.reindex(obj.index[2:])
|
413 |
+
tm.assert_equal(res, exp)
|
414 |
+
|
415 |
+
obj.loc[1:2] = 7
|
416 |
+
assert (obj.loc[1:2] == 7).values.all()
|
417 |
+
|
418 |
+
def test_setitem_change_dtype(self, multiindex_dataframe_random_data):
|
419 |
+
frame = multiindex_dataframe_random_data
|
420 |
+
dft = frame.T
|
421 |
+
s = dft["foo", "two"]
|
422 |
+
dft["foo", "two"] = s > s.median()
|
423 |
+
tm.assert_series_equal(dft["foo", "two"], s > s.median())
|
424 |
+
# assert isinstance(dft._data.blocks[1].items, MultiIndex)
|
425 |
+
|
426 |
+
reindexed = dft.reindex(columns=[("foo", "two")])
|
427 |
+
tm.assert_series_equal(reindexed["foo", "two"], s > s.median())
|
428 |
+
|
429 |
+
def test_set_column_scalar_with_loc(
|
430 |
+
self, multiindex_dataframe_random_data, using_copy_on_write, warn_copy_on_write
|
431 |
+
):
|
432 |
+
frame = multiindex_dataframe_random_data
|
433 |
+
subset = frame.index[[1, 4, 5]]
|
434 |
+
|
435 |
+
frame.loc[subset] = 99
|
436 |
+
assert (frame.loc[subset].values == 99).all()
|
437 |
+
|
438 |
+
frame_original = frame.copy()
|
439 |
+
col = frame["B"]
|
440 |
+
with tm.assert_cow_warning(warn_copy_on_write):
|
441 |
+
col[subset] = 97
|
442 |
+
if using_copy_on_write:
|
443 |
+
# chained setitem doesn't work with CoW
|
444 |
+
tm.assert_frame_equal(frame, frame_original)
|
445 |
+
else:
|
446 |
+
assert (frame.loc[subset, "B"] == 97).all()
|
447 |
+
|
448 |
+
def test_nonunique_assignment_1750(self):
|
449 |
+
df = DataFrame(
|
450 |
+
[[1, 1, "x", "X"], [1, 1, "y", "Y"], [1, 2, "z", "Z"]], columns=list("ABCD")
|
451 |
+
)
|
452 |
+
|
453 |
+
df = df.set_index(["A", "B"])
|
454 |
+
mi = MultiIndex.from_tuples([(1, 1)])
|
455 |
+
|
456 |
+
df.loc[mi, "C"] = "_"
|
457 |
+
|
458 |
+
assert (df.xs((1, 1))["C"] == "_").all()
|
459 |
+
|
460 |
+
def test_astype_assignment_with_dups(self):
|
461 |
+
# GH 4686
|
462 |
+
# assignment with dups that has a dtype change
|
463 |
+
cols = MultiIndex.from_tuples([("A", "1"), ("B", "1"), ("A", "2")])
|
464 |
+
df = DataFrame(np.arange(3).reshape((1, 3)), columns=cols, dtype=object)
|
465 |
+
index = df.index.copy()
|
466 |
+
|
467 |
+
df["A"] = df["A"].astype(np.float64)
|
468 |
+
tm.assert_index_equal(df.index, index)
|
469 |
+
|
470 |
+
def test_setitem_nonmonotonic(self):
|
471 |
+
# https://github.com/pandas-dev/pandas/issues/31449
|
472 |
+
index = MultiIndex.from_tuples(
|
473 |
+
[("a", "c"), ("b", "x"), ("a", "d")], names=["l1", "l2"]
|
474 |
+
)
|
475 |
+
df = DataFrame(data=[0, 1, 2], index=index, columns=["e"])
|
476 |
+
df.loc["a", "e"] = np.arange(99, 101, dtype="int64")
|
477 |
+
expected = DataFrame({"e": [99, 1, 100]}, index=index)
|
478 |
+
tm.assert_frame_equal(df, expected)
|
479 |
+
|
480 |
+
|
481 |
+
class TestSetitemWithExpansionMultiIndex:
|
482 |
+
def test_setitem_new_column_mixed_depth(self):
|
483 |
+
arrays = [
|
484 |
+
["a", "top", "top", "routine1", "routine1", "routine2"],
|
485 |
+
["", "OD", "OD", "result1", "result2", "result1"],
|
486 |
+
["", "wx", "wy", "", "", ""],
|
487 |
+
]
|
488 |
+
|
489 |
+
tuples = sorted(zip(*arrays))
|
490 |
+
index = MultiIndex.from_tuples(tuples)
|
491 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((4, 6)), columns=index)
|
492 |
+
|
493 |
+
result = df.copy()
|
494 |
+
expected = df.copy()
|
495 |
+
result["b"] = [1, 2, 3, 4]
|
496 |
+
expected["b", "", ""] = [1, 2, 3, 4]
|
497 |
+
tm.assert_frame_equal(result, expected)
|
498 |
+
|
499 |
+
def test_setitem_new_column_all_na(self):
|
500 |
+
# GH#1534
|
501 |
+
mix = MultiIndex.from_tuples([("1a", "2a"), ("1a", "2b"), ("1a", "2c")])
|
502 |
+
df = DataFrame([[1, 2], [3, 4], [5, 6]], index=mix)
|
503 |
+
s = Series({(1, 1): 1, (1, 2): 2})
|
504 |
+
df["new"] = s
|
505 |
+
assert df["new"].isna().all()
|
506 |
+
|
507 |
+
def test_setitem_enlargement_keep_index_names(self):
|
508 |
+
# GH#53053
|
509 |
+
mi = MultiIndex.from_tuples([(1, 2, 3)], names=["i1", "i2", "i3"])
|
510 |
+
df = DataFrame(data=[[10, 20, 30]], index=mi, columns=["A", "B", "C"])
|
511 |
+
df.loc[(0, 0, 0)] = df.loc[(1, 2, 3)]
|
512 |
+
mi_expected = MultiIndex.from_tuples(
|
513 |
+
[(1, 2, 3), (0, 0, 0)], names=["i1", "i2", "i3"]
|
514 |
+
)
|
515 |
+
expected = DataFrame(
|
516 |
+
data=[[10, 20, 30], [10, 20, 30]],
|
517 |
+
index=mi_expected,
|
518 |
+
columns=["A", "B", "C"],
|
519 |
+
)
|
520 |
+
tm.assert_frame_equal(df, expected)
|
521 |
+
|
522 |
+
|
523 |
+
@td.skip_array_manager_invalid_test # df["foo"] select multiple columns -> .values
|
524 |
+
# is not a view
|
525 |
+
def test_frame_setitem_view_direct(
|
526 |
+
multiindex_dataframe_random_data, using_copy_on_write
|
527 |
+
):
|
528 |
+
# this works because we are modifying the underlying array
|
529 |
+
# really a no-no
|
530 |
+
df = multiindex_dataframe_random_data.T
|
531 |
+
if using_copy_on_write:
|
532 |
+
with pytest.raises(ValueError, match="read-only"):
|
533 |
+
df["foo"].values[:] = 0
|
534 |
+
assert (df["foo"].values != 0).all()
|
535 |
+
else:
|
536 |
+
df["foo"].values[:] = 0
|
537 |
+
assert (df["foo"].values == 0).all()
|
538 |
+
|
539 |
+
|
540 |
+
def test_frame_setitem_copy_raises(
|
541 |
+
multiindex_dataframe_random_data, using_copy_on_write, warn_copy_on_write
|
542 |
+
):
|
543 |
+
# will raise/warn as its chained assignment
|
544 |
+
df = multiindex_dataframe_random_data.T
|
545 |
+
if using_copy_on_write or warn_copy_on_write:
|
546 |
+
with tm.raises_chained_assignment_error():
|
547 |
+
df["foo"]["one"] = 2
|
548 |
+
else:
|
549 |
+
msg = "A value is trying to be set on a copy of a slice from a DataFrame"
|
550 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
551 |
+
with tm.raises_chained_assignment_error():
|
552 |
+
df["foo"]["one"] = 2
|
553 |
+
|
554 |
+
|
555 |
+
def test_frame_setitem_copy_no_write(
|
556 |
+
multiindex_dataframe_random_data, using_copy_on_write, warn_copy_on_write
|
557 |
+
):
|
558 |
+
frame = multiindex_dataframe_random_data.T
|
559 |
+
expected = frame
|
560 |
+
df = frame.copy()
|
561 |
+
if using_copy_on_write or warn_copy_on_write:
|
562 |
+
with tm.raises_chained_assignment_error():
|
563 |
+
df["foo"]["one"] = 2
|
564 |
+
else:
|
565 |
+
msg = "A value is trying to be set on a copy of a slice from a DataFrame"
|
566 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
567 |
+
with tm.raises_chained_assignment_error():
|
568 |
+
df["foo"]["one"] = 2
|
569 |
+
|
570 |
+
result = df
|
571 |
+
tm.assert_frame_equal(result, expected)
|
572 |
+
|
573 |
+
|
574 |
+
def test_frame_setitem_partial_multiindex():
|
575 |
+
# GH 54875
|
576 |
+
df = DataFrame(
|
577 |
+
{
|
578 |
+
"a": [1, 2, 3],
|
579 |
+
"b": [3, 4, 5],
|
580 |
+
"c": 6,
|
581 |
+
"d": 7,
|
582 |
+
}
|
583 |
+
).set_index(["a", "b", "c"])
|
584 |
+
ser = Series(8, index=df.index.droplevel("c"))
|
585 |
+
result = df.copy()
|
586 |
+
result["d"] = ser
|
587 |
+
expected = df.copy()
|
588 |
+
expected["d"] = 8
|
589 |
+
tm.assert_frame_equal(result, expected)
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_slice.py
ADDED
@@ -0,0 +1,796 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from datetime import (
|
2 |
+
datetime,
|
3 |
+
timedelta,
|
4 |
+
)
|
5 |
+
|
6 |
+
import numpy as np
|
7 |
+
import pytest
|
8 |
+
|
9 |
+
from pandas.errors import UnsortedIndexError
|
10 |
+
|
11 |
+
import pandas as pd
|
12 |
+
from pandas import (
|
13 |
+
DataFrame,
|
14 |
+
Index,
|
15 |
+
MultiIndex,
|
16 |
+
Series,
|
17 |
+
Timestamp,
|
18 |
+
)
|
19 |
+
import pandas._testing as tm
|
20 |
+
from pandas.tests.indexing.common import _mklbl
|
21 |
+
|
22 |
+
|
23 |
+
class TestMultiIndexSlicers:
|
24 |
+
def test_per_axis_per_level_getitem(self):
|
25 |
+
# GH6134
|
26 |
+
# example test case
|
27 |
+
ix = MultiIndex.from_product(
|
28 |
+
[_mklbl("A", 5), _mklbl("B", 7), _mklbl("C", 4), _mklbl("D", 2)]
|
29 |
+
)
|
30 |
+
df = DataFrame(np.arange(len(ix.to_numpy())), index=ix)
|
31 |
+
|
32 |
+
result = df.loc[(slice("A1", "A3"), slice(None), ["C1", "C3"]), :]
|
33 |
+
expected = df.loc[
|
34 |
+
[
|
35 |
+
(
|
36 |
+
a,
|
37 |
+
b,
|
38 |
+
c,
|
39 |
+
d,
|
40 |
+
)
|
41 |
+
for a, b, c, d in df.index.values
|
42 |
+
if a in ("A1", "A2", "A3") and c in ("C1", "C3")
|
43 |
+
]
|
44 |
+
]
|
45 |
+
tm.assert_frame_equal(result, expected)
|
46 |
+
|
47 |
+
expected = df.loc[
|
48 |
+
[
|
49 |
+
(
|
50 |
+
a,
|
51 |
+
b,
|
52 |
+
c,
|
53 |
+
d,
|
54 |
+
)
|
55 |
+
for a, b, c, d in df.index.values
|
56 |
+
if a in ("A1", "A2", "A3") and c in ("C1", "C2", "C3")
|
57 |
+
]
|
58 |
+
]
|
59 |
+
result = df.loc[(slice("A1", "A3"), slice(None), slice("C1", "C3")), :]
|
60 |
+
tm.assert_frame_equal(result, expected)
|
61 |
+
|
62 |
+
# test multi-index slicing with per axis and per index controls
|
63 |
+
index = MultiIndex.from_tuples(
|
64 |
+
[("A", 1), ("A", 2), ("A", 3), ("B", 1)], names=["one", "two"]
|
65 |
+
)
|
66 |
+
columns = MultiIndex.from_tuples(
|
67 |
+
[("a", "foo"), ("a", "bar"), ("b", "foo"), ("b", "bah")],
|
68 |
+
names=["lvl0", "lvl1"],
|
69 |
+
)
|
70 |
+
|
71 |
+
df = DataFrame(
|
72 |
+
np.arange(16, dtype="int64").reshape(4, 4), index=index, columns=columns
|
73 |
+
)
|
74 |
+
df = df.sort_index(axis=0).sort_index(axis=1)
|
75 |
+
|
76 |
+
# identity
|
77 |
+
result = df.loc[(slice(None), slice(None)), :]
|
78 |
+
tm.assert_frame_equal(result, df)
|
79 |
+
result = df.loc[(slice(None), slice(None)), (slice(None), slice(None))]
|
80 |
+
tm.assert_frame_equal(result, df)
|
81 |
+
result = df.loc[:, (slice(None), slice(None))]
|
82 |
+
tm.assert_frame_equal(result, df)
|
83 |
+
|
84 |
+
# index
|
85 |
+
result = df.loc[(slice(None), [1]), :]
|
86 |
+
expected = df.iloc[[0, 3]]
|
87 |
+
tm.assert_frame_equal(result, expected)
|
88 |
+
|
89 |
+
result = df.loc[(slice(None), 1), :]
|
90 |
+
expected = df.iloc[[0, 3]]
|
91 |
+
tm.assert_frame_equal(result, expected)
|
92 |
+
|
93 |
+
# columns
|
94 |
+
result = df.loc[:, (slice(None), ["foo"])]
|
95 |
+
expected = df.iloc[:, [1, 3]]
|
96 |
+
tm.assert_frame_equal(result, expected)
|
97 |
+
|
98 |
+
# both
|
99 |
+
result = df.loc[(slice(None), 1), (slice(None), ["foo"])]
|
100 |
+
expected = df.iloc[[0, 3], [1, 3]]
|
101 |
+
tm.assert_frame_equal(result, expected)
|
102 |
+
|
103 |
+
result = df.loc["A", "a"]
|
104 |
+
expected = DataFrame(
|
105 |
+
{"bar": [1, 5, 9], "foo": [0, 4, 8]},
|
106 |
+
index=Index([1, 2, 3], name="two"),
|
107 |
+
columns=Index(["bar", "foo"], name="lvl1"),
|
108 |
+
)
|
109 |
+
tm.assert_frame_equal(result, expected)
|
110 |
+
|
111 |
+
result = df.loc[(slice(None), [1, 2]), :]
|
112 |
+
expected = df.iloc[[0, 1, 3]]
|
113 |
+
tm.assert_frame_equal(result, expected)
|
114 |
+
|
115 |
+
# multi-level series
|
116 |
+
s = Series(np.arange(len(ix.to_numpy())), index=ix)
|
117 |
+
result = s.loc["A1":"A3", :, ["C1", "C3"]]
|
118 |
+
expected = s.loc[
|
119 |
+
[
|
120 |
+
(
|
121 |
+
a,
|
122 |
+
b,
|
123 |
+
c,
|
124 |
+
d,
|
125 |
+
)
|
126 |
+
for a, b, c, d in s.index.values
|
127 |
+
if a in ("A1", "A2", "A3") and c in ("C1", "C3")
|
128 |
+
]
|
129 |
+
]
|
130 |
+
tm.assert_series_equal(result, expected)
|
131 |
+
|
132 |
+
# boolean indexers
|
133 |
+
result = df.loc[(slice(None), df.loc[:, ("a", "bar")] > 5), :]
|
134 |
+
expected = df.iloc[[2, 3]]
|
135 |
+
tm.assert_frame_equal(result, expected)
|
136 |
+
|
137 |
+
msg = (
|
138 |
+
"cannot index with a boolean indexer "
|
139 |
+
"that is not the same length as the index"
|
140 |
+
)
|
141 |
+
with pytest.raises(ValueError, match=msg):
|
142 |
+
df.loc[(slice(None), np.array([True, False])), :]
|
143 |
+
|
144 |
+
with pytest.raises(KeyError, match=r"\[1\] not in index"):
|
145 |
+
# slice(None) is on the index, [1] is on the columns, but 1 is
|
146 |
+
# not in the columns, so we raise
|
147 |
+
# This used to treat [1] as positional GH#16396
|
148 |
+
df.loc[slice(None), [1]]
|
149 |
+
|
150 |
+
# not lexsorted
|
151 |
+
assert df.index._lexsort_depth == 2
|
152 |
+
df = df.sort_index(level=1, axis=0)
|
153 |
+
assert df.index._lexsort_depth == 0
|
154 |
+
|
155 |
+
msg = (
|
156 |
+
"MultiIndex slicing requires the index to be "
|
157 |
+
r"lexsorted: slicing on levels \[1\], lexsort depth 0"
|
158 |
+
)
|
159 |
+
with pytest.raises(UnsortedIndexError, match=msg):
|
160 |
+
df.loc[(slice(None), slice("bar")), :]
|
161 |
+
|
162 |
+
# GH 16734: not sorted, but no real slicing
|
163 |
+
result = df.loc[(slice(None), df.loc[:, ("a", "bar")] > 5), :]
|
164 |
+
tm.assert_frame_equal(result, df.iloc[[1, 3], :])
|
165 |
+
|
166 |
+
def test_multiindex_slicers_non_unique(self):
|
167 |
+
# GH 7106
|
168 |
+
# non-unique mi index support
|
169 |
+
df = (
|
170 |
+
DataFrame(
|
171 |
+
{
|
172 |
+
"A": ["foo", "foo", "foo", "foo"],
|
173 |
+
"B": ["a", "a", "a", "a"],
|
174 |
+
"C": [1, 2, 1, 3],
|
175 |
+
"D": [1, 2, 3, 4],
|
176 |
+
}
|
177 |
+
)
|
178 |
+
.set_index(["A", "B", "C"])
|
179 |
+
.sort_index()
|
180 |
+
)
|
181 |
+
assert not df.index.is_unique
|
182 |
+
expected = (
|
183 |
+
DataFrame({"A": ["foo", "foo"], "B": ["a", "a"], "C": [1, 1], "D": [1, 3]})
|
184 |
+
.set_index(["A", "B", "C"])
|
185 |
+
.sort_index()
|
186 |
+
)
|
187 |
+
result = df.loc[(slice(None), slice(None), 1), :]
|
188 |
+
tm.assert_frame_equal(result, expected)
|
189 |
+
|
190 |
+
# this is equivalent of an xs expression
|
191 |
+
result = df.xs(1, level=2, drop_level=False)
|
192 |
+
tm.assert_frame_equal(result, expected)
|
193 |
+
|
194 |
+
df = (
|
195 |
+
DataFrame(
|
196 |
+
{
|
197 |
+
"A": ["foo", "foo", "foo", "foo"],
|
198 |
+
"B": ["a", "a", "a", "a"],
|
199 |
+
"C": [1, 2, 1, 2],
|
200 |
+
"D": [1, 2, 3, 4],
|
201 |
+
}
|
202 |
+
)
|
203 |
+
.set_index(["A", "B", "C"])
|
204 |
+
.sort_index()
|
205 |
+
)
|
206 |
+
assert not df.index.is_unique
|
207 |
+
expected = (
|
208 |
+
DataFrame({"A": ["foo", "foo"], "B": ["a", "a"], "C": [1, 1], "D": [1, 3]})
|
209 |
+
.set_index(["A", "B", "C"])
|
210 |
+
.sort_index()
|
211 |
+
)
|
212 |
+
result = df.loc[(slice(None), slice(None), 1), :]
|
213 |
+
assert not result.index.is_unique
|
214 |
+
tm.assert_frame_equal(result, expected)
|
215 |
+
|
216 |
+
# GH12896
|
217 |
+
# numpy-implementation dependent bug
|
218 |
+
ints = [
|
219 |
+
1,
|
220 |
+
2,
|
221 |
+
3,
|
222 |
+
4,
|
223 |
+
5,
|
224 |
+
6,
|
225 |
+
7,
|
226 |
+
8,
|
227 |
+
9,
|
228 |
+
10,
|
229 |
+
11,
|
230 |
+
12,
|
231 |
+
12,
|
232 |
+
13,
|
233 |
+
14,
|
234 |
+
14,
|
235 |
+
16,
|
236 |
+
17,
|
237 |
+
18,
|
238 |
+
19,
|
239 |
+
200000,
|
240 |
+
200000,
|
241 |
+
]
|
242 |
+
n = len(ints)
|
243 |
+
idx = MultiIndex.from_arrays([["a"] * n, ints])
|
244 |
+
result = Series([1] * n, index=idx)
|
245 |
+
result = result.sort_index()
|
246 |
+
result = result.loc[(slice(None), slice(100000))]
|
247 |
+
expected = Series([1] * (n - 2), index=idx[:-2]).sort_index()
|
248 |
+
tm.assert_series_equal(result, expected)
|
249 |
+
|
250 |
+
def test_multiindex_slicers_datetimelike(self):
|
251 |
+
# GH 7429
|
252 |
+
# buggy/inconsistent behavior when slicing with datetime-like
|
253 |
+
dates = [datetime(2012, 1, 1, 12, 12, 12) + timedelta(days=i) for i in range(6)]
|
254 |
+
freq = [1, 2]
|
255 |
+
index = MultiIndex.from_product([dates, freq], names=["date", "frequency"])
|
256 |
+
|
257 |
+
df = DataFrame(
|
258 |
+
np.arange(6 * 2 * 4, dtype="int64").reshape(-1, 4),
|
259 |
+
index=index,
|
260 |
+
columns=list("ABCD"),
|
261 |
+
)
|
262 |
+
|
263 |
+
# multi-axis slicing
|
264 |
+
idx = pd.IndexSlice
|
265 |
+
expected = df.iloc[[0, 2, 4], [0, 1]]
|
266 |
+
result = df.loc[
|
267 |
+
(
|
268 |
+
slice(
|
269 |
+
Timestamp("2012-01-01 12:12:12"), Timestamp("2012-01-03 12:12:12")
|
270 |
+
),
|
271 |
+
slice(1, 1),
|
272 |
+
),
|
273 |
+
slice("A", "B"),
|
274 |
+
]
|
275 |
+
tm.assert_frame_equal(result, expected)
|
276 |
+
|
277 |
+
result = df.loc[
|
278 |
+
(
|
279 |
+
idx[
|
280 |
+
Timestamp("2012-01-01 12:12:12") : Timestamp("2012-01-03 12:12:12")
|
281 |
+
],
|
282 |
+
idx[1:1],
|
283 |
+
),
|
284 |
+
slice("A", "B"),
|
285 |
+
]
|
286 |
+
tm.assert_frame_equal(result, expected)
|
287 |
+
|
288 |
+
result = df.loc[
|
289 |
+
(
|
290 |
+
slice(
|
291 |
+
Timestamp("2012-01-01 12:12:12"), Timestamp("2012-01-03 12:12:12")
|
292 |
+
),
|
293 |
+
1,
|
294 |
+
),
|
295 |
+
slice("A", "B"),
|
296 |
+
]
|
297 |
+
tm.assert_frame_equal(result, expected)
|
298 |
+
|
299 |
+
# with strings
|
300 |
+
result = df.loc[
|
301 |
+
(slice("2012-01-01 12:12:12", "2012-01-03 12:12:12"), slice(1, 1)),
|
302 |
+
slice("A", "B"),
|
303 |
+
]
|
304 |
+
tm.assert_frame_equal(result, expected)
|
305 |
+
|
306 |
+
result = df.loc[
|
307 |
+
(idx["2012-01-01 12:12:12":"2012-01-03 12:12:12"], 1), idx["A", "B"]
|
308 |
+
]
|
309 |
+
tm.assert_frame_equal(result, expected)
|
310 |
+
|
311 |
+
def test_multiindex_slicers_edges(self):
|
312 |
+
# GH 8132
|
313 |
+
# various edge cases
|
314 |
+
df = DataFrame(
|
315 |
+
{
|
316 |
+
"A": ["A0"] * 5 + ["A1"] * 5 + ["A2"] * 5,
|
317 |
+
"B": ["B0", "B0", "B1", "B1", "B2"] * 3,
|
318 |
+
"DATE": [
|
319 |
+
"2013-06-11",
|
320 |
+
"2013-07-02",
|
321 |
+
"2013-07-09",
|
322 |
+
"2013-07-30",
|
323 |
+
"2013-08-06",
|
324 |
+
"2013-06-11",
|
325 |
+
"2013-07-02",
|
326 |
+
"2013-07-09",
|
327 |
+
"2013-07-30",
|
328 |
+
"2013-08-06",
|
329 |
+
"2013-09-03",
|
330 |
+
"2013-10-01",
|
331 |
+
"2013-07-09",
|
332 |
+
"2013-08-06",
|
333 |
+
"2013-09-03",
|
334 |
+
],
|
335 |
+
"VALUES": [22, 35, 14, 9, 4, 40, 18, 4, 2, 5, 1, 2, 3, 4, 2],
|
336 |
+
}
|
337 |
+
)
|
338 |
+
|
339 |
+
df["DATE"] = pd.to_datetime(df["DATE"])
|
340 |
+
df1 = df.set_index(["A", "B", "DATE"])
|
341 |
+
df1 = df1.sort_index()
|
342 |
+
|
343 |
+
# A1 - Get all values under "A0" and "A1"
|
344 |
+
result = df1.loc[(slice("A1")), :]
|
345 |
+
expected = df1.iloc[0:10]
|
346 |
+
tm.assert_frame_equal(result, expected)
|
347 |
+
|
348 |
+
# A2 - Get all values from the start to "A2"
|
349 |
+
result = df1.loc[(slice("A2")), :]
|
350 |
+
expected = df1
|
351 |
+
tm.assert_frame_equal(result, expected)
|
352 |
+
|
353 |
+
# A3 - Get all values under "B1" or "B2"
|
354 |
+
result = df1.loc[(slice(None), slice("B1", "B2")), :]
|
355 |
+
expected = df1.iloc[[2, 3, 4, 7, 8, 9, 12, 13, 14]]
|
356 |
+
tm.assert_frame_equal(result, expected)
|
357 |
+
|
358 |
+
# A4 - Get all values between 2013-07-02 and 2013-07-09
|
359 |
+
result = df1.loc[(slice(None), slice(None), slice("20130702", "20130709")), :]
|
360 |
+
expected = df1.iloc[[1, 2, 6, 7, 12]]
|
361 |
+
tm.assert_frame_equal(result, expected)
|
362 |
+
|
363 |
+
# B1 - Get all values in B0 that are also under A0, A1 and A2
|
364 |
+
result = df1.loc[(slice("A2"), slice("B0")), :]
|
365 |
+
expected = df1.iloc[[0, 1, 5, 6, 10, 11]]
|
366 |
+
tm.assert_frame_equal(result, expected)
|
367 |
+
|
368 |
+
# B2 - Get all values in B0, B1 and B2 (similar to what #2 is doing for
|
369 |
+
# the As)
|
370 |
+
result = df1.loc[(slice(None), slice("B2")), :]
|
371 |
+
expected = df1
|
372 |
+
tm.assert_frame_equal(result, expected)
|
373 |
+
|
374 |
+
# B3 - Get all values from B1 to B2 and up to 2013-08-06
|
375 |
+
result = df1.loc[(slice(None), slice("B1", "B2"), slice("2013-08-06")), :]
|
376 |
+
expected = df1.iloc[[2, 3, 4, 7, 8, 9, 12, 13]]
|
377 |
+
tm.assert_frame_equal(result, expected)
|
378 |
+
|
379 |
+
# B4 - Same as A4 but the start of the date slice is not a key.
|
380 |
+
# shows indexing on a partial selection slice
|
381 |
+
result = df1.loc[(slice(None), slice(None), slice("20130701", "20130709")), :]
|
382 |
+
expected = df1.iloc[[1, 2, 6, 7, 12]]
|
383 |
+
tm.assert_frame_equal(result, expected)
|
384 |
+
|
385 |
+
def test_per_axis_per_level_doc_examples(self):
|
386 |
+
# test index maker
|
387 |
+
idx = pd.IndexSlice
|
388 |
+
|
389 |
+
# from indexing.rst / advanced
|
390 |
+
index = MultiIndex.from_product(
|
391 |
+
[_mklbl("A", 4), _mklbl("B", 2), _mklbl("C", 4), _mklbl("D", 2)]
|
392 |
+
)
|
393 |
+
columns = MultiIndex.from_tuples(
|
394 |
+
[("a", "foo"), ("a", "bar"), ("b", "foo"), ("b", "bah")],
|
395 |
+
names=["lvl0", "lvl1"],
|
396 |
+
)
|
397 |
+
df = DataFrame(
|
398 |
+
np.arange(len(index) * len(columns), dtype="int64").reshape(
|
399 |
+
(len(index), len(columns))
|
400 |
+
),
|
401 |
+
index=index,
|
402 |
+
columns=columns,
|
403 |
+
)
|
404 |
+
result = df.loc[(slice("A1", "A3"), slice(None), ["C1", "C3"]), :]
|
405 |
+
expected = df.loc[
|
406 |
+
[
|
407 |
+
(
|
408 |
+
a,
|
409 |
+
b,
|
410 |
+
c,
|
411 |
+
d,
|
412 |
+
)
|
413 |
+
for a, b, c, d in df.index.values
|
414 |
+
if a in ("A1", "A2", "A3") and c in ("C1", "C3")
|
415 |
+
]
|
416 |
+
]
|
417 |
+
tm.assert_frame_equal(result, expected)
|
418 |
+
result = df.loc[idx["A1":"A3", :, ["C1", "C3"]], :]
|
419 |
+
tm.assert_frame_equal(result, expected)
|
420 |
+
|
421 |
+
result = df.loc[(slice(None), slice(None), ["C1", "C3"]), :]
|
422 |
+
expected = df.loc[
|
423 |
+
[
|
424 |
+
(
|
425 |
+
a,
|
426 |
+
b,
|
427 |
+
c,
|
428 |
+
d,
|
429 |
+
)
|
430 |
+
for a, b, c, d in df.index.values
|
431 |
+
if c in ("C1", "C3")
|
432 |
+
]
|
433 |
+
]
|
434 |
+
tm.assert_frame_equal(result, expected)
|
435 |
+
result = df.loc[idx[:, :, ["C1", "C3"]], :]
|
436 |
+
tm.assert_frame_equal(result, expected)
|
437 |
+
|
438 |
+
# not sorted
|
439 |
+
msg = (
|
440 |
+
"MultiIndex slicing requires the index to be lexsorted: "
|
441 |
+
r"slicing on levels \[1\], lexsort depth 1"
|
442 |
+
)
|
443 |
+
with pytest.raises(UnsortedIndexError, match=msg):
|
444 |
+
df.loc["A1", ("a", slice("foo"))]
|
445 |
+
|
446 |
+
# GH 16734: not sorted, but no real slicing
|
447 |
+
tm.assert_frame_equal(
|
448 |
+
df.loc["A1", (slice(None), "foo")], df.loc["A1"].iloc[:, [0, 2]]
|
449 |
+
)
|
450 |
+
|
451 |
+
df = df.sort_index(axis=1)
|
452 |
+
|
453 |
+
# slicing
|
454 |
+
df.loc["A1", (slice(None), "foo")]
|
455 |
+
df.loc[(slice(None), slice(None), ["C1", "C3"]), (slice(None), "foo")]
|
456 |
+
|
457 |
+
# setitem
|
458 |
+
df.loc(axis=0)[:, :, ["C1", "C3"]] = -10
|
459 |
+
|
460 |
+
def test_loc_axis_arguments(self):
|
461 |
+
index = MultiIndex.from_product(
|
462 |
+
[_mklbl("A", 4), _mklbl("B", 2), _mklbl("C", 4), _mklbl("D", 2)]
|
463 |
+
)
|
464 |
+
columns = MultiIndex.from_tuples(
|
465 |
+
[("a", "foo"), ("a", "bar"), ("b", "foo"), ("b", "bah")],
|
466 |
+
names=["lvl0", "lvl1"],
|
467 |
+
)
|
468 |
+
df = (
|
469 |
+
DataFrame(
|
470 |
+
np.arange(len(index) * len(columns), dtype="int64").reshape(
|
471 |
+
(len(index), len(columns))
|
472 |
+
),
|
473 |
+
index=index,
|
474 |
+
columns=columns,
|
475 |
+
)
|
476 |
+
.sort_index()
|
477 |
+
.sort_index(axis=1)
|
478 |
+
)
|
479 |
+
|
480 |
+
# axis 0
|
481 |
+
result = df.loc(axis=0)["A1":"A3", :, ["C1", "C3"]]
|
482 |
+
expected = df.loc[
|
483 |
+
[
|
484 |
+
(
|
485 |
+
a,
|
486 |
+
b,
|
487 |
+
c,
|
488 |
+
d,
|
489 |
+
)
|
490 |
+
for a, b, c, d in df.index.values
|
491 |
+
if a in ("A1", "A2", "A3") and c in ("C1", "C3")
|
492 |
+
]
|
493 |
+
]
|
494 |
+
tm.assert_frame_equal(result, expected)
|
495 |
+
|
496 |
+
result = df.loc(axis="index")[:, :, ["C1", "C3"]]
|
497 |
+
expected = df.loc[
|
498 |
+
[
|
499 |
+
(
|
500 |
+
a,
|
501 |
+
b,
|
502 |
+
c,
|
503 |
+
d,
|
504 |
+
)
|
505 |
+
for a, b, c, d in df.index.values
|
506 |
+
if c in ("C1", "C3")
|
507 |
+
]
|
508 |
+
]
|
509 |
+
tm.assert_frame_equal(result, expected)
|
510 |
+
|
511 |
+
# axis 1
|
512 |
+
result = df.loc(axis=1)[:, "foo"]
|
513 |
+
expected = df.loc[:, (slice(None), "foo")]
|
514 |
+
tm.assert_frame_equal(result, expected)
|
515 |
+
|
516 |
+
result = df.loc(axis="columns")[:, "foo"]
|
517 |
+
expected = df.loc[:, (slice(None), "foo")]
|
518 |
+
tm.assert_frame_equal(result, expected)
|
519 |
+
|
520 |
+
# invalid axis
|
521 |
+
for i in [-1, 2, "foo"]:
|
522 |
+
msg = f"No axis named {i} for object type DataFrame"
|
523 |
+
with pytest.raises(ValueError, match=msg):
|
524 |
+
df.loc(axis=i)[:, :, ["C1", "C3"]]
|
525 |
+
|
526 |
+
def test_loc_axis_single_level_multi_col_indexing_multiindex_col_df(self):
|
527 |
+
# GH29519
|
528 |
+
df = DataFrame(
|
529 |
+
np.arange(27).reshape(3, 9),
|
530 |
+
columns=MultiIndex.from_product([["a1", "a2", "a3"], ["b1", "b2", "b3"]]),
|
531 |
+
)
|
532 |
+
result = df.loc(axis=1)["a1":"a2"]
|
533 |
+
expected = df.iloc[:, :-3]
|
534 |
+
|
535 |
+
tm.assert_frame_equal(result, expected)
|
536 |
+
|
537 |
+
def test_loc_axis_single_level_single_col_indexing_multiindex_col_df(self):
|
538 |
+
# GH29519
|
539 |
+
df = DataFrame(
|
540 |
+
np.arange(27).reshape(3, 9),
|
541 |
+
columns=MultiIndex.from_product([["a1", "a2", "a3"], ["b1", "b2", "b3"]]),
|
542 |
+
)
|
543 |
+
result = df.loc(axis=1)["a1"]
|
544 |
+
expected = df.iloc[:, :3]
|
545 |
+
expected.columns = ["b1", "b2", "b3"]
|
546 |
+
|
547 |
+
tm.assert_frame_equal(result, expected)
|
548 |
+
|
549 |
+
def test_loc_ax_single_level_indexer_simple_df(self):
|
550 |
+
# GH29519
|
551 |
+
# test single level indexing on single index column data frame
|
552 |
+
df = DataFrame(np.arange(9).reshape(3, 3), columns=["a", "b", "c"])
|
553 |
+
result = df.loc(axis=1)["a"]
|
554 |
+
expected = Series(np.array([0, 3, 6]), name="a")
|
555 |
+
tm.assert_series_equal(result, expected)
|
556 |
+
|
557 |
+
def test_per_axis_per_level_setitem(self):
|
558 |
+
# test index maker
|
559 |
+
idx = pd.IndexSlice
|
560 |
+
|
561 |
+
# test multi-index slicing with per axis and per index controls
|
562 |
+
index = MultiIndex.from_tuples(
|
563 |
+
[("A", 1), ("A", 2), ("A", 3), ("B", 1)], names=["one", "two"]
|
564 |
+
)
|
565 |
+
columns = MultiIndex.from_tuples(
|
566 |
+
[("a", "foo"), ("a", "bar"), ("b", "foo"), ("b", "bah")],
|
567 |
+
names=["lvl0", "lvl1"],
|
568 |
+
)
|
569 |
+
|
570 |
+
df_orig = DataFrame(
|
571 |
+
np.arange(16, dtype="int64").reshape(4, 4), index=index, columns=columns
|
572 |
+
)
|
573 |
+
df_orig = df_orig.sort_index(axis=0).sort_index(axis=1)
|
574 |
+
|
575 |
+
# identity
|
576 |
+
df = df_orig.copy()
|
577 |
+
df.loc[(slice(None), slice(None)), :] = 100
|
578 |
+
expected = df_orig.copy()
|
579 |
+
expected.iloc[:, :] = 100
|
580 |
+
tm.assert_frame_equal(df, expected)
|
581 |
+
|
582 |
+
df = df_orig.copy()
|
583 |
+
df.loc(axis=0)[:, :] = 100
|
584 |
+
expected = df_orig.copy()
|
585 |
+
expected.iloc[:, :] = 100
|
586 |
+
tm.assert_frame_equal(df, expected)
|
587 |
+
|
588 |
+
df = df_orig.copy()
|
589 |
+
df.loc[(slice(None), slice(None)), (slice(None), slice(None))] = 100
|
590 |
+
expected = df_orig.copy()
|
591 |
+
expected.iloc[:, :] = 100
|
592 |
+
tm.assert_frame_equal(df, expected)
|
593 |
+
|
594 |
+
df = df_orig.copy()
|
595 |
+
df.loc[:, (slice(None), slice(None))] = 100
|
596 |
+
expected = df_orig.copy()
|
597 |
+
expected.iloc[:, :] = 100
|
598 |
+
tm.assert_frame_equal(df, expected)
|
599 |
+
|
600 |
+
# index
|
601 |
+
df = df_orig.copy()
|
602 |
+
df.loc[(slice(None), [1]), :] = 100
|
603 |
+
expected = df_orig.copy()
|
604 |
+
expected.iloc[[0, 3]] = 100
|
605 |
+
tm.assert_frame_equal(df, expected)
|
606 |
+
|
607 |
+
df = df_orig.copy()
|
608 |
+
df.loc[(slice(None), 1), :] = 100
|
609 |
+
expected = df_orig.copy()
|
610 |
+
expected.iloc[[0, 3]] = 100
|
611 |
+
tm.assert_frame_equal(df, expected)
|
612 |
+
|
613 |
+
df = df_orig.copy()
|
614 |
+
df.loc(axis=0)[:, 1] = 100
|
615 |
+
expected = df_orig.copy()
|
616 |
+
expected.iloc[[0, 3]] = 100
|
617 |
+
tm.assert_frame_equal(df, expected)
|
618 |
+
|
619 |
+
# columns
|
620 |
+
df = df_orig.copy()
|
621 |
+
df.loc[:, (slice(None), ["foo"])] = 100
|
622 |
+
expected = df_orig.copy()
|
623 |
+
expected.iloc[:, [1, 3]] = 100
|
624 |
+
tm.assert_frame_equal(df, expected)
|
625 |
+
|
626 |
+
# both
|
627 |
+
df = df_orig.copy()
|
628 |
+
df.loc[(slice(None), 1), (slice(None), ["foo"])] = 100
|
629 |
+
expected = df_orig.copy()
|
630 |
+
expected.iloc[[0, 3], [1, 3]] = 100
|
631 |
+
tm.assert_frame_equal(df, expected)
|
632 |
+
|
633 |
+
df = df_orig.copy()
|
634 |
+
df.loc[idx[:, 1], idx[:, ["foo"]]] = 100
|
635 |
+
expected = df_orig.copy()
|
636 |
+
expected.iloc[[0, 3], [1, 3]] = 100
|
637 |
+
tm.assert_frame_equal(df, expected)
|
638 |
+
|
639 |
+
df = df_orig.copy()
|
640 |
+
df.loc["A", "a"] = 100
|
641 |
+
expected = df_orig.copy()
|
642 |
+
expected.iloc[0:3, 0:2] = 100
|
643 |
+
tm.assert_frame_equal(df, expected)
|
644 |
+
|
645 |
+
# setting with a list-like
|
646 |
+
df = df_orig.copy()
|
647 |
+
df.loc[(slice(None), 1), (slice(None), ["foo"])] = np.array(
|
648 |
+
[[100, 100], [100, 100]], dtype="int64"
|
649 |
+
)
|
650 |
+
expected = df_orig.copy()
|
651 |
+
expected.iloc[[0, 3], [1, 3]] = 100
|
652 |
+
tm.assert_frame_equal(df, expected)
|
653 |
+
|
654 |
+
# not enough values
|
655 |
+
df = df_orig.copy()
|
656 |
+
|
657 |
+
msg = "setting an array element with a sequence."
|
658 |
+
with pytest.raises(ValueError, match=msg):
|
659 |
+
df.loc[(slice(None), 1), (slice(None), ["foo"])] = np.array(
|
660 |
+
[[100], [100, 100]], dtype="int64"
|
661 |
+
)
|
662 |
+
|
663 |
+
msg = "Must have equal len keys and value when setting with an iterable"
|
664 |
+
with pytest.raises(ValueError, match=msg):
|
665 |
+
df.loc[(slice(None), 1), (slice(None), ["foo"])] = np.array(
|
666 |
+
[100, 100, 100, 100], dtype="int64"
|
667 |
+
)
|
668 |
+
|
669 |
+
# with an alignable rhs
|
670 |
+
df = df_orig.copy()
|
671 |
+
df.loc[(slice(None), 1), (slice(None), ["foo"])] = (
|
672 |
+
df.loc[(slice(None), 1), (slice(None), ["foo"])] * 5
|
673 |
+
)
|
674 |
+
expected = df_orig.copy()
|
675 |
+
expected.iloc[[0, 3], [1, 3]] = expected.iloc[[0, 3], [1, 3]] * 5
|
676 |
+
tm.assert_frame_equal(df, expected)
|
677 |
+
|
678 |
+
df = df_orig.copy()
|
679 |
+
df.loc[(slice(None), 1), (slice(None), ["foo"])] *= df.loc[
|
680 |
+
(slice(None), 1), (slice(None), ["foo"])
|
681 |
+
]
|
682 |
+
expected = df_orig.copy()
|
683 |
+
expected.iloc[[0, 3], [1, 3]] *= expected.iloc[[0, 3], [1, 3]]
|
684 |
+
tm.assert_frame_equal(df, expected)
|
685 |
+
|
686 |
+
rhs = df_orig.loc[(slice(None), 1), (slice(None), ["foo"])].copy()
|
687 |
+
rhs.loc[:, ("c", "bah")] = 10
|
688 |
+
df = df_orig.copy()
|
689 |
+
df.loc[(slice(None), 1), (slice(None), ["foo"])] *= rhs
|
690 |
+
expected = df_orig.copy()
|
691 |
+
expected.iloc[[0, 3], [1, 3]] *= expected.iloc[[0, 3], [1, 3]]
|
692 |
+
tm.assert_frame_equal(df, expected)
|
693 |
+
|
694 |
+
def test_multiindex_label_slicing_with_negative_step(self):
|
695 |
+
ser = Series(
|
696 |
+
np.arange(20), MultiIndex.from_product([list("abcde"), np.arange(4)])
|
697 |
+
)
|
698 |
+
SLC = pd.IndexSlice
|
699 |
+
|
700 |
+
tm.assert_indexing_slices_equivalent(ser, SLC[::-1], SLC[::-1])
|
701 |
+
|
702 |
+
tm.assert_indexing_slices_equivalent(ser, SLC["d"::-1], SLC[15::-1])
|
703 |
+
tm.assert_indexing_slices_equivalent(ser, SLC[("d",)::-1], SLC[15::-1])
|
704 |
+
|
705 |
+
tm.assert_indexing_slices_equivalent(ser, SLC[:"d":-1], SLC[:11:-1])
|
706 |
+
tm.assert_indexing_slices_equivalent(ser, SLC[:("d",):-1], SLC[:11:-1])
|
707 |
+
|
708 |
+
tm.assert_indexing_slices_equivalent(ser, SLC["d":"b":-1], SLC[15:3:-1])
|
709 |
+
tm.assert_indexing_slices_equivalent(ser, SLC[("d",):"b":-1], SLC[15:3:-1])
|
710 |
+
tm.assert_indexing_slices_equivalent(ser, SLC["d":("b",):-1], SLC[15:3:-1])
|
711 |
+
tm.assert_indexing_slices_equivalent(ser, SLC[("d",):("b",):-1], SLC[15:3:-1])
|
712 |
+
tm.assert_indexing_slices_equivalent(ser, SLC["b":"d":-1], SLC[:0])
|
713 |
+
|
714 |
+
tm.assert_indexing_slices_equivalent(ser, SLC[("c", 2)::-1], SLC[10::-1])
|
715 |
+
tm.assert_indexing_slices_equivalent(ser, SLC[:("c", 2):-1], SLC[:9:-1])
|
716 |
+
tm.assert_indexing_slices_equivalent(
|
717 |
+
ser, SLC[("e", 0):("c", 2):-1], SLC[16:9:-1]
|
718 |
+
)
|
719 |
+
|
720 |
+
def test_multiindex_slice_first_level(self):
|
721 |
+
# GH 12697
|
722 |
+
freq = ["a", "b", "c", "d"]
|
723 |
+
idx = MultiIndex.from_product([freq, range(500)])
|
724 |
+
df = DataFrame(list(range(2000)), index=idx, columns=["Test"])
|
725 |
+
df_slice = df.loc[pd.IndexSlice[:, 30:70], :]
|
726 |
+
result = df_slice.loc["a"]
|
727 |
+
expected = DataFrame(list(range(30, 71)), columns=["Test"], index=range(30, 71))
|
728 |
+
tm.assert_frame_equal(result, expected)
|
729 |
+
result = df_slice.loc["d"]
|
730 |
+
expected = DataFrame(
|
731 |
+
list(range(1530, 1571)), columns=["Test"], index=range(30, 71)
|
732 |
+
)
|
733 |
+
tm.assert_frame_equal(result, expected)
|
734 |
+
|
735 |
+
def test_int_series_slicing(self, multiindex_year_month_day_dataframe_random_data):
|
736 |
+
ymd = multiindex_year_month_day_dataframe_random_data
|
737 |
+
s = ymd["A"]
|
738 |
+
result = s[5:]
|
739 |
+
expected = s.reindex(s.index[5:])
|
740 |
+
tm.assert_series_equal(result, expected)
|
741 |
+
|
742 |
+
s = ymd["A"].copy()
|
743 |
+
exp = ymd["A"].copy()
|
744 |
+
s[5:] = 0
|
745 |
+
exp.iloc[5:] = 0
|
746 |
+
tm.assert_numpy_array_equal(s.values, exp.values)
|
747 |
+
|
748 |
+
result = ymd[5:]
|
749 |
+
expected = ymd.reindex(s.index[5:])
|
750 |
+
tm.assert_frame_equal(result, expected)
|
751 |
+
|
752 |
+
@pytest.mark.parametrize(
|
753 |
+
"dtype, loc, iloc",
|
754 |
+
[
|
755 |
+
# dtype = int, step = -1
|
756 |
+
("int", slice(None, None, -1), slice(None, None, -1)),
|
757 |
+
("int", slice(3, None, -1), slice(3, None, -1)),
|
758 |
+
("int", slice(None, 1, -1), slice(None, 0, -1)),
|
759 |
+
("int", slice(3, 1, -1), slice(3, 0, -1)),
|
760 |
+
# dtype = int, step = -2
|
761 |
+
("int", slice(None, None, -2), slice(None, None, -2)),
|
762 |
+
("int", slice(3, None, -2), slice(3, None, -2)),
|
763 |
+
("int", slice(None, 1, -2), slice(None, 0, -2)),
|
764 |
+
("int", slice(3, 1, -2), slice(3, 0, -2)),
|
765 |
+
# dtype = str, step = -1
|
766 |
+
("str", slice(None, None, -1), slice(None, None, -1)),
|
767 |
+
("str", slice("d", None, -1), slice(3, None, -1)),
|
768 |
+
("str", slice(None, "b", -1), slice(None, 0, -1)),
|
769 |
+
("str", slice("d", "b", -1), slice(3, 0, -1)),
|
770 |
+
# dtype = str, step = -2
|
771 |
+
("str", slice(None, None, -2), slice(None, None, -2)),
|
772 |
+
("str", slice("d", None, -2), slice(3, None, -2)),
|
773 |
+
("str", slice(None, "b", -2), slice(None, 0, -2)),
|
774 |
+
("str", slice("d", "b", -2), slice(3, 0, -2)),
|
775 |
+
],
|
776 |
+
)
|
777 |
+
def test_loc_slice_negative_stepsize(self, dtype, loc, iloc):
|
778 |
+
# GH#38071
|
779 |
+
labels = {
|
780 |
+
"str": list("abcde"),
|
781 |
+
"int": range(5),
|
782 |
+
}[dtype]
|
783 |
+
|
784 |
+
mi = MultiIndex.from_arrays([labels] * 2)
|
785 |
+
df = DataFrame(1.0, index=mi, columns=["A"])
|
786 |
+
|
787 |
+
SLC = pd.IndexSlice
|
788 |
+
|
789 |
+
expected = df.iloc[iloc, :]
|
790 |
+
result_get_loc = df.loc[SLC[loc], :]
|
791 |
+
result_get_locs_level_0 = df.loc[SLC[loc, :], :]
|
792 |
+
result_get_locs_level_1 = df.loc[SLC[:, loc], :]
|
793 |
+
|
794 |
+
tm.assert_frame_equal(result_get_loc, expected)
|
795 |
+
tm.assert_frame_equal(result_get_locs_level_0, expected)
|
796 |
+
tm.assert_frame_equal(result_get_locs_level_1, expected)
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_sorted.py
ADDED
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas import (
|
5 |
+
NA,
|
6 |
+
DataFrame,
|
7 |
+
MultiIndex,
|
8 |
+
Series,
|
9 |
+
array,
|
10 |
+
)
|
11 |
+
import pandas._testing as tm
|
12 |
+
|
13 |
+
|
14 |
+
class TestMultiIndexSorted:
|
15 |
+
def test_getitem_multilevel_index_tuple_not_sorted(self):
|
16 |
+
index_columns = list("abc")
|
17 |
+
df = DataFrame(
|
18 |
+
[[0, 1, 0, "x"], [0, 0, 1, "y"]], columns=index_columns + ["data"]
|
19 |
+
)
|
20 |
+
df = df.set_index(index_columns)
|
21 |
+
query_index = df.index[:1]
|
22 |
+
rs = df.loc[query_index, "data"]
|
23 |
+
|
24 |
+
xp_idx = MultiIndex.from_tuples([(0, 1, 0)], names=["a", "b", "c"])
|
25 |
+
xp = Series(["x"], index=xp_idx, name="data")
|
26 |
+
tm.assert_series_equal(rs, xp)
|
27 |
+
|
28 |
+
def test_getitem_slice_not_sorted(self, multiindex_dataframe_random_data):
|
29 |
+
frame = multiindex_dataframe_random_data
|
30 |
+
df = frame.sort_index(level=1).T
|
31 |
+
|
32 |
+
# buglet with int typechecking
|
33 |
+
result = df.iloc[:, : np.int32(3)]
|
34 |
+
expected = df.reindex(columns=df.columns[:3])
|
35 |
+
tm.assert_frame_equal(result, expected)
|
36 |
+
|
37 |
+
@pytest.mark.parametrize("key", [None, lambda x: x])
|
38 |
+
def test_frame_getitem_not_sorted2(self, key):
|
39 |
+
# 13431
|
40 |
+
df = DataFrame(
|
41 |
+
{
|
42 |
+
"col1": ["b", "d", "b", "a"],
|
43 |
+
"col2": [3, 1, 1, 2],
|
44 |
+
"data": ["one", "two", "three", "four"],
|
45 |
+
}
|
46 |
+
)
|
47 |
+
|
48 |
+
df2 = df.set_index(["col1", "col2"])
|
49 |
+
df2_original = df2.copy()
|
50 |
+
|
51 |
+
df2.index = df2.index.set_levels(["b", "d", "a"], level="col1")
|
52 |
+
df2.index = df2.index.set_codes([0, 1, 0, 2], level="col1")
|
53 |
+
assert not df2.index.is_monotonic_increasing
|
54 |
+
|
55 |
+
assert df2_original.index.equals(df2.index)
|
56 |
+
expected = df2.sort_index(key=key)
|
57 |
+
assert expected.index.is_monotonic_increasing
|
58 |
+
|
59 |
+
result = df2.sort_index(level=0, key=key)
|
60 |
+
assert result.index.is_monotonic_increasing
|
61 |
+
tm.assert_frame_equal(result, expected)
|
62 |
+
|
63 |
+
def test_sort_values_key(self):
|
64 |
+
arrays = [
|
65 |
+
["bar", "bar", "baz", "baz", "qux", "qux", "foo", "foo"],
|
66 |
+
["one", "two", "one", "two", "one", "two", "one", "two"],
|
67 |
+
]
|
68 |
+
tuples = zip(*arrays)
|
69 |
+
index = MultiIndex.from_tuples(tuples)
|
70 |
+
index = index.sort_values( # sort by third letter
|
71 |
+
key=lambda x: x.map(lambda entry: entry[2])
|
72 |
+
)
|
73 |
+
result = DataFrame(range(8), index=index)
|
74 |
+
|
75 |
+
arrays = [
|
76 |
+
["foo", "foo", "bar", "bar", "qux", "qux", "baz", "baz"],
|
77 |
+
["one", "two", "one", "two", "one", "two", "one", "two"],
|
78 |
+
]
|
79 |
+
tuples = zip(*arrays)
|
80 |
+
index = MultiIndex.from_tuples(tuples)
|
81 |
+
expected = DataFrame(range(8), index=index)
|
82 |
+
|
83 |
+
tm.assert_frame_equal(result, expected)
|
84 |
+
|
85 |
+
def test_argsort_with_na(self):
|
86 |
+
# GH48495
|
87 |
+
arrays = [
|
88 |
+
array([2, NA, 1], dtype="Int64"),
|
89 |
+
array([1, 2, 3], dtype="Int64"),
|
90 |
+
]
|
91 |
+
index = MultiIndex.from_arrays(arrays)
|
92 |
+
result = index.argsort()
|
93 |
+
expected = np.array([2, 0, 1], dtype=np.intp)
|
94 |
+
tm.assert_numpy_array_equal(result, expected)
|
95 |
+
|
96 |
+
def test_sort_values_with_na(self):
|
97 |
+
# GH48495
|
98 |
+
arrays = [
|
99 |
+
array([2, NA, 1], dtype="Int64"),
|
100 |
+
array([1, 2, 3], dtype="Int64"),
|
101 |
+
]
|
102 |
+
index = MultiIndex.from_arrays(arrays)
|
103 |
+
index = index.sort_values()
|
104 |
+
result = DataFrame(range(3), index=index)
|
105 |
+
|
106 |
+
arrays = [
|
107 |
+
array([1, 2, NA], dtype="Int64"),
|
108 |
+
array([3, 1, 2], dtype="Int64"),
|
109 |
+
]
|
110 |
+
index = MultiIndex.from_arrays(arrays)
|
111 |
+
expected = DataFrame(range(3), index=index)
|
112 |
+
|
113 |
+
tm.assert_frame_equal(result, expected)
|
114 |
+
|
115 |
+
def test_frame_getitem_not_sorted(self, multiindex_dataframe_random_data):
|
116 |
+
frame = multiindex_dataframe_random_data
|
117 |
+
df = frame.T
|
118 |
+
df["foo", "four"] = "foo"
|
119 |
+
|
120 |
+
arrays = [np.array(x) for x in zip(*df.columns.values)]
|
121 |
+
|
122 |
+
result = df["foo"]
|
123 |
+
result2 = df.loc[:, "foo"]
|
124 |
+
expected = df.reindex(columns=df.columns[arrays[0] == "foo"])
|
125 |
+
expected.columns = expected.columns.droplevel(0)
|
126 |
+
tm.assert_frame_equal(result, expected)
|
127 |
+
tm.assert_frame_equal(result2, expected)
|
128 |
+
|
129 |
+
df = df.T
|
130 |
+
result = df.xs("foo")
|
131 |
+
result2 = df.loc["foo"]
|
132 |
+
expected = df.reindex(df.index[arrays[0] == "foo"])
|
133 |
+
expected.index = expected.index.droplevel(0)
|
134 |
+
tm.assert_frame_equal(result, expected)
|
135 |
+
tm.assert_frame_equal(result2, expected)
|
136 |
+
|
137 |
+
def test_series_getitem_not_sorted(self):
|
138 |
+
arrays = [
|
139 |
+
["bar", "bar", "baz", "baz", "qux", "qux", "foo", "foo"],
|
140 |
+
["one", "two", "one", "two", "one", "two", "one", "two"],
|
141 |
+
]
|
142 |
+
tuples = zip(*arrays)
|
143 |
+
index = MultiIndex.from_tuples(tuples)
|
144 |
+
s = Series(np.random.default_rng(2).standard_normal(8), index=index)
|
145 |
+
|
146 |
+
arrays = [np.array(x) for x in zip(*index.values)]
|
147 |
+
|
148 |
+
result = s["qux"]
|
149 |
+
result2 = s.loc["qux"]
|
150 |
+
expected = s[arrays[0] == "qux"]
|
151 |
+
expected.index = expected.index.droplevel(0)
|
152 |
+
tm.assert_series_equal(result, expected)
|
153 |
+
tm.assert_series_equal(result2, expected)
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/test_at.py
ADDED
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from datetime import (
|
2 |
+
datetime,
|
3 |
+
timezone,
|
4 |
+
)
|
5 |
+
|
6 |
+
import numpy as np
|
7 |
+
import pytest
|
8 |
+
|
9 |
+
from pandas.errors import InvalidIndexError
|
10 |
+
|
11 |
+
from pandas import (
|
12 |
+
CategoricalDtype,
|
13 |
+
CategoricalIndex,
|
14 |
+
DataFrame,
|
15 |
+
DatetimeIndex,
|
16 |
+
Index,
|
17 |
+
MultiIndex,
|
18 |
+
Series,
|
19 |
+
Timestamp,
|
20 |
+
)
|
21 |
+
import pandas._testing as tm
|
22 |
+
|
23 |
+
|
24 |
+
def test_at_timezone():
|
25 |
+
# https://github.com/pandas-dev/pandas/issues/33544
|
26 |
+
result = DataFrame({"foo": [datetime(2000, 1, 1)]})
|
27 |
+
with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):
|
28 |
+
result.at[0, "foo"] = datetime(2000, 1, 2, tzinfo=timezone.utc)
|
29 |
+
expected = DataFrame(
|
30 |
+
{"foo": [datetime(2000, 1, 2, tzinfo=timezone.utc)]}, dtype=object
|
31 |
+
)
|
32 |
+
tm.assert_frame_equal(result, expected)
|
33 |
+
|
34 |
+
|
35 |
+
def test_selection_methods_of_assigned_col():
|
36 |
+
# GH 29282
|
37 |
+
df = DataFrame(data={"a": [1, 2, 3], "b": [4, 5, 6]})
|
38 |
+
df2 = DataFrame(data={"c": [7, 8, 9]}, index=[2, 1, 0])
|
39 |
+
df["c"] = df2["c"]
|
40 |
+
df.at[1, "c"] = 11
|
41 |
+
result = df
|
42 |
+
expected = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [9, 11, 7]})
|
43 |
+
tm.assert_frame_equal(result, expected)
|
44 |
+
result = df.at[1, "c"]
|
45 |
+
assert result == 11
|
46 |
+
|
47 |
+
result = df["c"]
|
48 |
+
expected = Series([9, 11, 7], name="c")
|
49 |
+
tm.assert_series_equal(result, expected)
|
50 |
+
|
51 |
+
result = df[["c"]]
|
52 |
+
expected = DataFrame({"c": [9, 11, 7]})
|
53 |
+
tm.assert_frame_equal(result, expected)
|
54 |
+
|
55 |
+
|
56 |
+
class TestAtSetItem:
|
57 |
+
def test_at_setitem_item_cache_cleared(self):
|
58 |
+
# GH#22372 Note the multi-step construction is necessary to trigger
|
59 |
+
# the original bug. pandas/issues/22372#issuecomment-413345309
|
60 |
+
df = DataFrame(index=[0])
|
61 |
+
df["x"] = 1
|
62 |
+
df["cost"] = 2
|
63 |
+
|
64 |
+
# accessing df["cost"] adds "cost" to the _item_cache
|
65 |
+
df["cost"]
|
66 |
+
|
67 |
+
# This loc[[0]] lookup used to call _consolidate_inplace at the
|
68 |
+
# BlockManager level, which failed to clear the _item_cache
|
69 |
+
df.loc[[0]]
|
70 |
+
|
71 |
+
df.at[0, "x"] = 4
|
72 |
+
df.at[0, "cost"] = 789
|
73 |
+
|
74 |
+
expected = DataFrame(
|
75 |
+
{"x": [4], "cost": 789},
|
76 |
+
index=[0],
|
77 |
+
columns=Index(["x", "cost"], dtype=object),
|
78 |
+
)
|
79 |
+
tm.assert_frame_equal(df, expected)
|
80 |
+
|
81 |
+
# And in particular, check that the _item_cache has updated correctly.
|
82 |
+
tm.assert_series_equal(df["cost"], expected["cost"])
|
83 |
+
|
84 |
+
def test_at_setitem_mixed_index_assignment(self):
|
85 |
+
# GH#19860
|
86 |
+
ser = Series([1, 2, 3, 4, 5], index=["a", "b", "c", 1, 2])
|
87 |
+
ser.at["a"] = 11
|
88 |
+
assert ser.iat[0] == 11
|
89 |
+
ser.at[1] = 22
|
90 |
+
assert ser.iat[3] == 22
|
91 |
+
|
92 |
+
def test_at_setitem_categorical_missing(self):
|
93 |
+
df = DataFrame(
|
94 |
+
index=range(3), columns=range(3), dtype=CategoricalDtype(["foo", "bar"])
|
95 |
+
)
|
96 |
+
df.at[1, 1] = "foo"
|
97 |
+
|
98 |
+
expected = DataFrame(
|
99 |
+
[
|
100 |
+
[np.nan, np.nan, np.nan],
|
101 |
+
[np.nan, "foo", np.nan],
|
102 |
+
[np.nan, np.nan, np.nan],
|
103 |
+
],
|
104 |
+
dtype=CategoricalDtype(["foo", "bar"]),
|
105 |
+
)
|
106 |
+
|
107 |
+
tm.assert_frame_equal(df, expected)
|
108 |
+
|
109 |
+
def test_at_setitem_multiindex(self):
|
110 |
+
df = DataFrame(
|
111 |
+
np.zeros((3, 2), dtype="int64"),
|
112 |
+
columns=MultiIndex.from_tuples([("a", 0), ("a", 1)]),
|
113 |
+
)
|
114 |
+
df.at[0, "a"] = 10
|
115 |
+
expected = DataFrame(
|
116 |
+
[[10, 10], [0, 0], [0, 0]],
|
117 |
+
columns=MultiIndex.from_tuples([("a", 0), ("a", 1)]),
|
118 |
+
)
|
119 |
+
tm.assert_frame_equal(df, expected)
|
120 |
+
|
121 |
+
@pytest.mark.parametrize("row", (Timestamp("2019-01-01"), "2019-01-01"))
|
122 |
+
def test_at_datetime_index(self, row):
|
123 |
+
# Set float64 dtype to avoid upcast when setting .5
|
124 |
+
df = DataFrame(
|
125 |
+
data=[[1] * 2], index=DatetimeIndex(data=["2019-01-01", "2019-01-02"])
|
126 |
+
).astype({0: "float64"})
|
127 |
+
expected = DataFrame(
|
128 |
+
data=[[0.5, 1], [1.0, 1]],
|
129 |
+
index=DatetimeIndex(data=["2019-01-01", "2019-01-02"]),
|
130 |
+
)
|
131 |
+
|
132 |
+
df.at[row, 0] = 0.5
|
133 |
+
tm.assert_frame_equal(df, expected)
|
134 |
+
|
135 |
+
|
136 |
+
class TestAtSetItemWithExpansion:
|
137 |
+
def test_at_setitem_expansion_series_dt64tz_value(self, tz_naive_fixture):
|
138 |
+
# GH#25506
|
139 |
+
ts = Timestamp("2017-08-05 00:00:00+0100", tz=tz_naive_fixture)
|
140 |
+
result = Series(ts)
|
141 |
+
result.at[1] = ts
|
142 |
+
expected = Series([ts, ts])
|
143 |
+
tm.assert_series_equal(result, expected)
|
144 |
+
|
145 |
+
|
146 |
+
class TestAtWithDuplicates:
|
147 |
+
def test_at_with_duplicate_axes_requires_scalar_lookup(self):
|
148 |
+
# GH#33041 check that falling back to loc doesn't allow non-scalar
|
149 |
+
# args to slip in
|
150 |
+
|
151 |
+
arr = np.random.default_rng(2).standard_normal(6).reshape(3, 2)
|
152 |
+
df = DataFrame(arr, columns=["A", "A"])
|
153 |
+
|
154 |
+
msg = "Invalid call for scalar access"
|
155 |
+
with pytest.raises(ValueError, match=msg):
|
156 |
+
df.at[[1, 2]]
|
157 |
+
with pytest.raises(ValueError, match=msg):
|
158 |
+
df.at[1, ["A"]]
|
159 |
+
with pytest.raises(ValueError, match=msg):
|
160 |
+
df.at[:, "A"]
|
161 |
+
|
162 |
+
with pytest.raises(ValueError, match=msg):
|
163 |
+
df.at[[1, 2]] = 1
|
164 |
+
with pytest.raises(ValueError, match=msg):
|
165 |
+
df.at[1, ["A"]] = 1
|
166 |
+
with pytest.raises(ValueError, match=msg):
|
167 |
+
df.at[:, "A"] = 1
|
168 |
+
|
169 |
+
|
170 |
+
class TestAtErrors:
|
171 |
+
# TODO: De-duplicate/parametrize
|
172 |
+
# test_at_series_raises_key_error2, test_at_frame_raises_key_error2
|
173 |
+
|
174 |
+
def test_at_series_raises_key_error(self, indexer_al):
|
175 |
+
# GH#31724 .at should match .loc
|
176 |
+
|
177 |
+
ser = Series([1, 2, 3], index=[3, 2, 1])
|
178 |
+
result = indexer_al(ser)[1]
|
179 |
+
assert result == 3
|
180 |
+
|
181 |
+
with pytest.raises(KeyError, match="a"):
|
182 |
+
indexer_al(ser)["a"]
|
183 |
+
|
184 |
+
def test_at_frame_raises_key_error(self, indexer_al):
|
185 |
+
# GH#31724 .at should match .loc
|
186 |
+
|
187 |
+
df = DataFrame({0: [1, 2, 3]}, index=[3, 2, 1])
|
188 |
+
|
189 |
+
result = indexer_al(df)[1, 0]
|
190 |
+
assert result == 3
|
191 |
+
|
192 |
+
with pytest.raises(KeyError, match="a"):
|
193 |
+
indexer_al(df)["a", 0]
|
194 |
+
|
195 |
+
with pytest.raises(KeyError, match="a"):
|
196 |
+
indexer_al(df)[1, "a"]
|
197 |
+
|
198 |
+
def test_at_series_raises_key_error2(self, indexer_al):
|
199 |
+
# at should not fallback
|
200 |
+
# GH#7814
|
201 |
+
# GH#31724 .at should match .loc
|
202 |
+
ser = Series([1, 2, 3], index=list("abc"))
|
203 |
+
result = indexer_al(ser)["a"]
|
204 |
+
assert result == 1
|
205 |
+
|
206 |
+
with pytest.raises(KeyError, match="^0$"):
|
207 |
+
indexer_al(ser)[0]
|
208 |
+
|
209 |
+
def test_at_frame_raises_key_error2(self, indexer_al):
|
210 |
+
# GH#31724 .at should match .loc
|
211 |
+
df = DataFrame({"A": [1, 2, 3]}, index=list("abc"))
|
212 |
+
result = indexer_al(df)["a", "A"]
|
213 |
+
assert result == 1
|
214 |
+
|
215 |
+
with pytest.raises(KeyError, match="^0$"):
|
216 |
+
indexer_al(df)["a", 0]
|
217 |
+
|
218 |
+
def test_at_frame_multiple_columns(self):
|
219 |
+
# GH#48296 - at shouldn't modify multiple columns
|
220 |
+
df = DataFrame({"a": [1, 2], "b": [3, 4]})
|
221 |
+
new_row = [6, 7]
|
222 |
+
with pytest.raises(
|
223 |
+
InvalidIndexError,
|
224 |
+
match=f"You can only assign a scalar value not a \\{type(new_row)}",
|
225 |
+
):
|
226 |
+
df.at[5] = new_row
|
227 |
+
|
228 |
+
def test_at_getitem_mixed_index_no_fallback(self):
|
229 |
+
# GH#19860
|
230 |
+
ser = Series([1, 2, 3, 4, 5], index=["a", "b", "c", 1, 2])
|
231 |
+
with pytest.raises(KeyError, match="^0$"):
|
232 |
+
ser.at[0]
|
233 |
+
with pytest.raises(KeyError, match="^4$"):
|
234 |
+
ser.at[4]
|
235 |
+
|
236 |
+
def test_at_categorical_integers(self):
|
237 |
+
# CategoricalIndex with integer categories that don't happen to match
|
238 |
+
# the Categorical's codes
|
239 |
+
ci = CategoricalIndex([3, 4])
|
240 |
+
|
241 |
+
arr = np.arange(4).reshape(2, 2)
|
242 |
+
frame = DataFrame(arr, index=ci)
|
243 |
+
|
244 |
+
for df in [frame, frame.T]:
|
245 |
+
for key in [0, 1]:
|
246 |
+
with pytest.raises(KeyError, match=str(key)):
|
247 |
+
df.at[key, key]
|
248 |
+
|
249 |
+
def test_at_applied_for_rows(self):
|
250 |
+
# GH#48729 .at should raise InvalidIndexError when assigning rows
|
251 |
+
df = DataFrame(index=["a"], columns=["col1", "col2"])
|
252 |
+
new_row = [123, 15]
|
253 |
+
with pytest.raises(
|
254 |
+
InvalidIndexError,
|
255 |
+
match=f"You can only assign a scalar value not a \\{type(new_row)}",
|
256 |
+
):
|
257 |
+
df.at["a"] = new_row
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/test_categorical.py
ADDED
@@ -0,0 +1,573 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
import pytest
|
5 |
+
|
6 |
+
import pandas.util._test_decorators as td
|
7 |
+
|
8 |
+
import pandas as pd
|
9 |
+
from pandas import (
|
10 |
+
Categorical,
|
11 |
+
CategoricalDtype,
|
12 |
+
CategoricalIndex,
|
13 |
+
DataFrame,
|
14 |
+
Index,
|
15 |
+
Interval,
|
16 |
+
Series,
|
17 |
+
Timedelta,
|
18 |
+
Timestamp,
|
19 |
+
option_context,
|
20 |
+
)
|
21 |
+
import pandas._testing as tm
|
22 |
+
|
23 |
+
|
24 |
+
@pytest.fixture
|
25 |
+
def df():
|
26 |
+
return DataFrame(
|
27 |
+
{
|
28 |
+
"A": np.arange(6, dtype="int64"),
|
29 |
+
},
|
30 |
+
index=CategoricalIndex(
|
31 |
+
list("aabbca"), dtype=CategoricalDtype(list("cab")), name="B"
|
32 |
+
),
|
33 |
+
)
|
34 |
+
|
35 |
+
|
36 |
+
@pytest.fixture
|
37 |
+
def df2():
|
38 |
+
return DataFrame(
|
39 |
+
{
|
40 |
+
"A": np.arange(6, dtype="int64"),
|
41 |
+
},
|
42 |
+
index=CategoricalIndex(
|
43 |
+
list("aabbca"), dtype=CategoricalDtype(list("cabe")), name="B"
|
44 |
+
),
|
45 |
+
)
|
46 |
+
|
47 |
+
|
48 |
+
class TestCategoricalIndex:
|
49 |
+
def test_loc_scalar(self, df):
|
50 |
+
dtype = CategoricalDtype(list("cab"))
|
51 |
+
result = df.loc["a"]
|
52 |
+
bidx = Series(list("aaa"), name="B").astype(dtype)
|
53 |
+
assert bidx.dtype == dtype
|
54 |
+
|
55 |
+
expected = DataFrame({"A": [0, 1, 5]}, index=Index(bidx))
|
56 |
+
tm.assert_frame_equal(result, expected)
|
57 |
+
|
58 |
+
df = df.copy()
|
59 |
+
df.loc["a"] = 20
|
60 |
+
bidx2 = Series(list("aabbca"), name="B").astype(dtype)
|
61 |
+
assert bidx2.dtype == dtype
|
62 |
+
expected = DataFrame(
|
63 |
+
{
|
64 |
+
"A": [20, 20, 2, 3, 4, 20],
|
65 |
+
},
|
66 |
+
index=Index(bidx2),
|
67 |
+
)
|
68 |
+
tm.assert_frame_equal(df, expected)
|
69 |
+
|
70 |
+
# value not in the categories
|
71 |
+
with pytest.raises(KeyError, match=r"^'d'$"):
|
72 |
+
df.loc["d"]
|
73 |
+
|
74 |
+
df2 = df.copy()
|
75 |
+
expected = df2.copy()
|
76 |
+
expected.index = expected.index.astype(object)
|
77 |
+
expected.loc["d"] = 10
|
78 |
+
df2.loc["d"] = 10
|
79 |
+
tm.assert_frame_equal(df2, expected)
|
80 |
+
|
81 |
+
def test_loc_setitem_with_expansion_non_category(self, df):
|
82 |
+
# Setting-with-expansion with a new key "d" that is not among caegories
|
83 |
+
df.loc["a"] = 20
|
84 |
+
|
85 |
+
# Setting a new row on an existing column
|
86 |
+
df3 = df.copy()
|
87 |
+
df3.loc["d", "A"] = 10
|
88 |
+
bidx3 = Index(list("aabbcad"), name="B")
|
89 |
+
expected3 = DataFrame(
|
90 |
+
{
|
91 |
+
"A": [20, 20, 2, 3, 4, 20, 10.0],
|
92 |
+
},
|
93 |
+
index=Index(bidx3),
|
94 |
+
)
|
95 |
+
tm.assert_frame_equal(df3, expected3)
|
96 |
+
|
97 |
+
# Setting a new row _and_ new column
|
98 |
+
df4 = df.copy()
|
99 |
+
df4.loc["d", "C"] = 10
|
100 |
+
expected3 = DataFrame(
|
101 |
+
{
|
102 |
+
"A": [20, 20, 2, 3, 4, 20, np.nan],
|
103 |
+
"C": [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, 10],
|
104 |
+
},
|
105 |
+
index=Index(bidx3),
|
106 |
+
)
|
107 |
+
tm.assert_frame_equal(df4, expected3)
|
108 |
+
|
109 |
+
def test_loc_getitem_scalar_non_category(self, df):
|
110 |
+
with pytest.raises(KeyError, match="^1$"):
|
111 |
+
df.loc[1]
|
112 |
+
|
113 |
+
def test_slicing(self):
|
114 |
+
cat = Series(Categorical([1, 2, 3, 4]))
|
115 |
+
reverse = cat[::-1]
|
116 |
+
exp = np.array([4, 3, 2, 1], dtype=np.int64)
|
117 |
+
tm.assert_numpy_array_equal(reverse.__array__(), exp)
|
118 |
+
|
119 |
+
df = DataFrame({"value": (np.arange(100) + 1).astype("int64")})
|
120 |
+
df["D"] = pd.cut(df.value, bins=[0, 25, 50, 75, 100])
|
121 |
+
|
122 |
+
expected = Series([11, Interval(0, 25)], index=["value", "D"], name=10)
|
123 |
+
result = df.iloc[10]
|
124 |
+
tm.assert_series_equal(result, expected)
|
125 |
+
|
126 |
+
expected = DataFrame(
|
127 |
+
{"value": np.arange(11, 21).astype("int64")},
|
128 |
+
index=np.arange(10, 20).astype("int64"),
|
129 |
+
)
|
130 |
+
expected["D"] = pd.cut(expected.value, bins=[0, 25, 50, 75, 100])
|
131 |
+
result = df.iloc[10:20]
|
132 |
+
tm.assert_frame_equal(result, expected)
|
133 |
+
|
134 |
+
expected = Series([9, Interval(0, 25)], index=["value", "D"], name=8)
|
135 |
+
result = df.loc[8]
|
136 |
+
tm.assert_series_equal(result, expected)
|
137 |
+
|
138 |
+
def test_slicing_and_getting_ops(self):
|
139 |
+
# systematically test the slicing operations:
|
140 |
+
# for all slicing ops:
|
141 |
+
# - returning a dataframe
|
142 |
+
# - returning a column
|
143 |
+
# - returning a row
|
144 |
+
# - returning a single value
|
145 |
+
|
146 |
+
cats = Categorical(
|
147 |
+
["a", "c", "b", "c", "c", "c", "c"], categories=["a", "b", "c"]
|
148 |
+
)
|
149 |
+
idx = Index(["h", "i", "j", "k", "l", "m", "n"])
|
150 |
+
values = [1, 2, 3, 4, 5, 6, 7]
|
151 |
+
df = DataFrame({"cats": cats, "values": values}, index=idx)
|
152 |
+
|
153 |
+
# the expected values
|
154 |
+
cats2 = Categorical(["b", "c"], categories=["a", "b", "c"])
|
155 |
+
idx2 = Index(["j", "k"])
|
156 |
+
values2 = [3, 4]
|
157 |
+
|
158 |
+
# 2:4,: | "j":"k",:
|
159 |
+
exp_df = DataFrame({"cats": cats2, "values": values2}, index=idx2)
|
160 |
+
|
161 |
+
# :,"cats" | :,0
|
162 |
+
exp_col = Series(cats, index=idx, name="cats")
|
163 |
+
|
164 |
+
# "j",: | 2,:
|
165 |
+
exp_row = Series(["b", 3], index=["cats", "values"], dtype="object", name="j")
|
166 |
+
|
167 |
+
# "j","cats | 2,0
|
168 |
+
exp_val = "b"
|
169 |
+
|
170 |
+
# iloc
|
171 |
+
# frame
|
172 |
+
res_df = df.iloc[2:4, :]
|
173 |
+
tm.assert_frame_equal(res_df, exp_df)
|
174 |
+
assert isinstance(res_df["cats"].dtype, CategoricalDtype)
|
175 |
+
|
176 |
+
# row
|
177 |
+
res_row = df.iloc[2, :]
|
178 |
+
tm.assert_series_equal(res_row, exp_row)
|
179 |
+
assert isinstance(res_row["cats"], str)
|
180 |
+
|
181 |
+
# col
|
182 |
+
res_col = df.iloc[:, 0]
|
183 |
+
tm.assert_series_equal(res_col, exp_col)
|
184 |
+
assert isinstance(res_col.dtype, CategoricalDtype)
|
185 |
+
|
186 |
+
# single value
|
187 |
+
res_val = df.iloc[2, 0]
|
188 |
+
assert res_val == exp_val
|
189 |
+
|
190 |
+
# loc
|
191 |
+
# frame
|
192 |
+
res_df = df.loc["j":"k", :]
|
193 |
+
tm.assert_frame_equal(res_df, exp_df)
|
194 |
+
assert isinstance(res_df["cats"].dtype, CategoricalDtype)
|
195 |
+
|
196 |
+
# row
|
197 |
+
res_row = df.loc["j", :]
|
198 |
+
tm.assert_series_equal(res_row, exp_row)
|
199 |
+
assert isinstance(res_row["cats"], str)
|
200 |
+
|
201 |
+
# col
|
202 |
+
res_col = df.loc[:, "cats"]
|
203 |
+
tm.assert_series_equal(res_col, exp_col)
|
204 |
+
assert isinstance(res_col.dtype, CategoricalDtype)
|
205 |
+
|
206 |
+
# single value
|
207 |
+
res_val = df.loc["j", "cats"]
|
208 |
+
assert res_val == exp_val
|
209 |
+
|
210 |
+
# single value
|
211 |
+
res_val = df.loc["j", df.columns[0]]
|
212 |
+
assert res_val == exp_val
|
213 |
+
|
214 |
+
# iat
|
215 |
+
res_val = df.iat[2, 0]
|
216 |
+
assert res_val == exp_val
|
217 |
+
|
218 |
+
# at
|
219 |
+
res_val = df.at["j", "cats"]
|
220 |
+
assert res_val == exp_val
|
221 |
+
|
222 |
+
# fancy indexing
|
223 |
+
exp_fancy = df.iloc[[2]]
|
224 |
+
|
225 |
+
res_fancy = df[df["cats"] == "b"]
|
226 |
+
tm.assert_frame_equal(res_fancy, exp_fancy)
|
227 |
+
res_fancy = df[df["values"] == 3]
|
228 |
+
tm.assert_frame_equal(res_fancy, exp_fancy)
|
229 |
+
|
230 |
+
# get_value
|
231 |
+
res_val = df.at["j", "cats"]
|
232 |
+
assert res_val == exp_val
|
233 |
+
|
234 |
+
# i : int, slice, or sequence of integers
|
235 |
+
res_row = df.iloc[2]
|
236 |
+
tm.assert_series_equal(res_row, exp_row)
|
237 |
+
assert isinstance(res_row["cats"], str)
|
238 |
+
|
239 |
+
res_df = df.iloc[slice(2, 4)]
|
240 |
+
tm.assert_frame_equal(res_df, exp_df)
|
241 |
+
assert isinstance(res_df["cats"].dtype, CategoricalDtype)
|
242 |
+
|
243 |
+
res_df = df.iloc[[2, 3]]
|
244 |
+
tm.assert_frame_equal(res_df, exp_df)
|
245 |
+
assert isinstance(res_df["cats"].dtype, CategoricalDtype)
|
246 |
+
|
247 |
+
res_col = df.iloc[:, 0]
|
248 |
+
tm.assert_series_equal(res_col, exp_col)
|
249 |
+
assert isinstance(res_col.dtype, CategoricalDtype)
|
250 |
+
|
251 |
+
res_df = df.iloc[:, slice(0, 2)]
|
252 |
+
tm.assert_frame_equal(res_df, df)
|
253 |
+
assert isinstance(res_df["cats"].dtype, CategoricalDtype)
|
254 |
+
|
255 |
+
res_df = df.iloc[:, [0, 1]]
|
256 |
+
tm.assert_frame_equal(res_df, df)
|
257 |
+
assert isinstance(res_df["cats"].dtype, CategoricalDtype)
|
258 |
+
|
259 |
+
def test_slicing_doc_examples(self):
|
260 |
+
# GH 7918
|
261 |
+
cats = Categorical(
|
262 |
+
["a", "b", "b", "b", "c", "c", "c"], categories=["a", "b", "c"]
|
263 |
+
)
|
264 |
+
idx = Index(["h", "i", "j", "k", "l", "m", "n"])
|
265 |
+
values = [1, 2, 2, 2, 3, 4, 5]
|
266 |
+
df = DataFrame({"cats": cats, "values": values}, index=idx)
|
267 |
+
|
268 |
+
result = df.iloc[2:4, :]
|
269 |
+
expected = DataFrame(
|
270 |
+
{
|
271 |
+
"cats": Categorical(["b", "b"], categories=["a", "b", "c"]),
|
272 |
+
"values": [2, 2],
|
273 |
+
},
|
274 |
+
index=["j", "k"],
|
275 |
+
)
|
276 |
+
tm.assert_frame_equal(result, expected)
|
277 |
+
|
278 |
+
result = df.iloc[2:4, :].dtypes
|
279 |
+
expected = Series(["category", "int64"], ["cats", "values"], dtype=object)
|
280 |
+
tm.assert_series_equal(result, expected)
|
281 |
+
|
282 |
+
result = df.loc["h":"j", "cats"]
|
283 |
+
expected = Series(
|
284 |
+
Categorical(["a", "b", "b"], categories=["a", "b", "c"]),
|
285 |
+
index=["h", "i", "j"],
|
286 |
+
name="cats",
|
287 |
+
)
|
288 |
+
tm.assert_series_equal(result, expected)
|
289 |
+
|
290 |
+
result = df.loc["h":"j", df.columns[0:1]]
|
291 |
+
expected = DataFrame(
|
292 |
+
{"cats": Categorical(["a", "b", "b"], categories=["a", "b", "c"])},
|
293 |
+
index=["h", "i", "j"],
|
294 |
+
)
|
295 |
+
tm.assert_frame_equal(result, expected)
|
296 |
+
|
297 |
+
def test_loc_getitem_listlike_labels(self, df):
|
298 |
+
# list of labels
|
299 |
+
result = df.loc[["c", "a"]]
|
300 |
+
expected = df.iloc[[4, 0, 1, 5]]
|
301 |
+
tm.assert_frame_equal(result, expected, check_index_type=True)
|
302 |
+
|
303 |
+
def test_loc_getitem_listlike_unused_category(self, df2):
|
304 |
+
# GH#37901 a label that is in index.categories but not in index
|
305 |
+
# listlike containing an element in the categories but not in the values
|
306 |
+
with pytest.raises(KeyError, match=re.escape("['e'] not in index")):
|
307 |
+
df2.loc[["a", "b", "e"]]
|
308 |
+
|
309 |
+
def test_loc_getitem_label_unused_category(self, df2):
|
310 |
+
# element in the categories but not in the values
|
311 |
+
with pytest.raises(KeyError, match=r"^'e'$"):
|
312 |
+
df2.loc["e"]
|
313 |
+
|
314 |
+
def test_loc_getitem_non_category(self, df2):
|
315 |
+
# not all labels in the categories
|
316 |
+
with pytest.raises(KeyError, match=re.escape("['d'] not in index")):
|
317 |
+
df2.loc[["a", "d"]]
|
318 |
+
|
319 |
+
def test_loc_setitem_expansion_label_unused_category(self, df2):
|
320 |
+
# assigning with a label that is in the categories but not in the index
|
321 |
+
df = df2.copy()
|
322 |
+
df.loc["e"] = 20
|
323 |
+
result = df.loc[["a", "b", "e"]]
|
324 |
+
exp_index = CategoricalIndex(list("aaabbe"), categories=list("cabe"), name="B")
|
325 |
+
expected = DataFrame({"A": [0, 1, 5, 2, 3, 20]}, index=exp_index)
|
326 |
+
tm.assert_frame_equal(result, expected)
|
327 |
+
|
328 |
+
def test_loc_listlike_dtypes(self):
|
329 |
+
# GH 11586
|
330 |
+
|
331 |
+
# unique categories and codes
|
332 |
+
index = CategoricalIndex(["a", "b", "c"])
|
333 |
+
df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}, index=index)
|
334 |
+
|
335 |
+
# unique slice
|
336 |
+
res = df.loc[["a", "b"]]
|
337 |
+
exp_index = CategoricalIndex(["a", "b"], categories=index.categories)
|
338 |
+
exp = DataFrame({"A": [1, 2], "B": [4, 5]}, index=exp_index)
|
339 |
+
tm.assert_frame_equal(res, exp, check_index_type=True)
|
340 |
+
|
341 |
+
# duplicated slice
|
342 |
+
res = df.loc[["a", "a", "b"]]
|
343 |
+
|
344 |
+
exp_index = CategoricalIndex(["a", "a", "b"], categories=index.categories)
|
345 |
+
exp = DataFrame({"A": [1, 1, 2], "B": [4, 4, 5]}, index=exp_index)
|
346 |
+
tm.assert_frame_equal(res, exp, check_index_type=True)
|
347 |
+
|
348 |
+
with pytest.raises(KeyError, match=re.escape("['x'] not in index")):
|
349 |
+
df.loc[["a", "x"]]
|
350 |
+
|
351 |
+
def test_loc_listlike_dtypes_duplicated_categories_and_codes(self):
|
352 |
+
# duplicated categories and codes
|
353 |
+
index = CategoricalIndex(["a", "b", "a"])
|
354 |
+
df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}, index=index)
|
355 |
+
|
356 |
+
# unique slice
|
357 |
+
res = df.loc[["a", "b"]]
|
358 |
+
exp = DataFrame(
|
359 |
+
{"A": [1, 3, 2], "B": [4, 6, 5]}, index=CategoricalIndex(["a", "a", "b"])
|
360 |
+
)
|
361 |
+
tm.assert_frame_equal(res, exp, check_index_type=True)
|
362 |
+
|
363 |
+
# duplicated slice
|
364 |
+
res = df.loc[["a", "a", "b"]]
|
365 |
+
exp = DataFrame(
|
366 |
+
{"A": [1, 3, 1, 3, 2], "B": [4, 6, 4, 6, 5]},
|
367 |
+
index=CategoricalIndex(["a", "a", "a", "a", "b"]),
|
368 |
+
)
|
369 |
+
tm.assert_frame_equal(res, exp, check_index_type=True)
|
370 |
+
|
371 |
+
with pytest.raises(KeyError, match=re.escape("['x'] not in index")):
|
372 |
+
df.loc[["a", "x"]]
|
373 |
+
|
374 |
+
def test_loc_listlike_dtypes_unused_category(self):
|
375 |
+
# contains unused category
|
376 |
+
index = CategoricalIndex(["a", "b", "a", "c"], categories=list("abcde"))
|
377 |
+
df = DataFrame({"A": [1, 2, 3, 4], "B": [5, 6, 7, 8]}, index=index)
|
378 |
+
|
379 |
+
res = df.loc[["a", "b"]]
|
380 |
+
exp = DataFrame(
|
381 |
+
{"A": [1, 3, 2], "B": [5, 7, 6]},
|
382 |
+
index=CategoricalIndex(["a", "a", "b"], categories=list("abcde")),
|
383 |
+
)
|
384 |
+
tm.assert_frame_equal(res, exp, check_index_type=True)
|
385 |
+
|
386 |
+
# duplicated slice
|
387 |
+
res = df.loc[["a", "a", "b"]]
|
388 |
+
exp = DataFrame(
|
389 |
+
{"A": [1, 3, 1, 3, 2], "B": [5, 7, 5, 7, 6]},
|
390 |
+
index=CategoricalIndex(["a", "a", "a", "a", "b"], categories=list("abcde")),
|
391 |
+
)
|
392 |
+
tm.assert_frame_equal(res, exp, check_index_type=True)
|
393 |
+
|
394 |
+
with pytest.raises(KeyError, match=re.escape("['x'] not in index")):
|
395 |
+
df.loc[["a", "x"]]
|
396 |
+
|
397 |
+
def test_loc_getitem_listlike_unused_category_raises_keyerror(self):
|
398 |
+
# key that is an *unused* category raises
|
399 |
+
index = CategoricalIndex(["a", "b", "a", "c"], categories=list("abcde"))
|
400 |
+
df = DataFrame({"A": [1, 2, 3, 4], "B": [5, 6, 7, 8]}, index=index)
|
401 |
+
|
402 |
+
with pytest.raises(KeyError, match="e"):
|
403 |
+
# For comparison, check the scalar behavior
|
404 |
+
df.loc["e"]
|
405 |
+
|
406 |
+
with pytest.raises(KeyError, match=re.escape("['e'] not in index")):
|
407 |
+
df.loc[["a", "e"]]
|
408 |
+
|
409 |
+
def test_ix_categorical_index(self):
|
410 |
+
# GH 12531
|
411 |
+
df = DataFrame(
|
412 |
+
np.random.default_rng(2).standard_normal((3, 3)),
|
413 |
+
index=list("ABC"),
|
414 |
+
columns=list("XYZ"),
|
415 |
+
)
|
416 |
+
cdf = df.copy()
|
417 |
+
cdf.index = CategoricalIndex(df.index)
|
418 |
+
cdf.columns = CategoricalIndex(df.columns)
|
419 |
+
|
420 |
+
expect = Series(df.loc["A", :], index=cdf.columns, name="A")
|
421 |
+
tm.assert_series_equal(cdf.loc["A", :], expect)
|
422 |
+
|
423 |
+
expect = Series(df.loc[:, "X"], index=cdf.index, name="X")
|
424 |
+
tm.assert_series_equal(cdf.loc[:, "X"], expect)
|
425 |
+
|
426 |
+
exp_index = CategoricalIndex(list("AB"), categories=["A", "B", "C"])
|
427 |
+
expect = DataFrame(df.loc[["A", "B"], :], columns=cdf.columns, index=exp_index)
|
428 |
+
tm.assert_frame_equal(cdf.loc[["A", "B"], :], expect)
|
429 |
+
|
430 |
+
exp_columns = CategoricalIndex(list("XY"), categories=["X", "Y", "Z"])
|
431 |
+
expect = DataFrame(df.loc[:, ["X", "Y"]], index=cdf.index, columns=exp_columns)
|
432 |
+
tm.assert_frame_equal(cdf.loc[:, ["X", "Y"]], expect)
|
433 |
+
|
434 |
+
@pytest.mark.parametrize(
|
435 |
+
"infer_string", [False, pytest.param(True, marks=td.skip_if_no("pyarrow"))]
|
436 |
+
)
|
437 |
+
def test_ix_categorical_index_non_unique(self, infer_string):
|
438 |
+
# non-unique
|
439 |
+
with option_context("future.infer_string", infer_string):
|
440 |
+
df = DataFrame(
|
441 |
+
np.random.default_rng(2).standard_normal((3, 3)),
|
442 |
+
index=list("ABA"),
|
443 |
+
columns=list("XYX"),
|
444 |
+
)
|
445 |
+
cdf = df.copy()
|
446 |
+
cdf.index = CategoricalIndex(df.index)
|
447 |
+
cdf.columns = CategoricalIndex(df.columns)
|
448 |
+
|
449 |
+
exp_index = CategoricalIndex(list("AA"), categories=["A", "B"])
|
450 |
+
expect = DataFrame(df.loc["A", :], columns=cdf.columns, index=exp_index)
|
451 |
+
tm.assert_frame_equal(cdf.loc["A", :], expect)
|
452 |
+
|
453 |
+
exp_columns = CategoricalIndex(list("XX"), categories=["X", "Y"])
|
454 |
+
expect = DataFrame(df.loc[:, "X"], index=cdf.index, columns=exp_columns)
|
455 |
+
tm.assert_frame_equal(cdf.loc[:, "X"], expect)
|
456 |
+
|
457 |
+
expect = DataFrame(
|
458 |
+
df.loc[["A", "B"], :],
|
459 |
+
columns=cdf.columns,
|
460 |
+
index=CategoricalIndex(list("AAB")),
|
461 |
+
)
|
462 |
+
tm.assert_frame_equal(cdf.loc[["A", "B"], :], expect)
|
463 |
+
|
464 |
+
expect = DataFrame(
|
465 |
+
df.loc[:, ["X", "Y"]],
|
466 |
+
index=cdf.index,
|
467 |
+
columns=CategoricalIndex(list("XXY")),
|
468 |
+
)
|
469 |
+
tm.assert_frame_equal(cdf.loc[:, ["X", "Y"]], expect)
|
470 |
+
|
471 |
+
def test_loc_slice(self, df):
|
472 |
+
# GH9748
|
473 |
+
msg = (
|
474 |
+
"cannot do slice indexing on CategoricalIndex with these "
|
475 |
+
r"indexers \[1\] of type int"
|
476 |
+
)
|
477 |
+
with pytest.raises(TypeError, match=msg):
|
478 |
+
df.loc[1:5]
|
479 |
+
|
480 |
+
result = df.loc["b":"c"]
|
481 |
+
expected = df.iloc[[2, 3, 4]]
|
482 |
+
tm.assert_frame_equal(result, expected)
|
483 |
+
|
484 |
+
def test_loc_and_at_with_categorical_index(self):
|
485 |
+
# GH 20629
|
486 |
+
df = DataFrame(
|
487 |
+
[[1, 2], [3, 4], [5, 6]], index=CategoricalIndex(["A", "B", "C"])
|
488 |
+
)
|
489 |
+
|
490 |
+
s = df[0]
|
491 |
+
assert s.loc["A"] == 1
|
492 |
+
assert s.at["A"] == 1
|
493 |
+
|
494 |
+
assert df.loc["B", 1] == 4
|
495 |
+
assert df.at["B", 1] == 4
|
496 |
+
|
497 |
+
@pytest.mark.parametrize(
|
498 |
+
"idx_values",
|
499 |
+
[
|
500 |
+
# python types
|
501 |
+
[1, 2, 3],
|
502 |
+
[-1, -2, -3],
|
503 |
+
[1.5, 2.5, 3.5],
|
504 |
+
[-1.5, -2.5, -3.5],
|
505 |
+
# numpy int/uint
|
506 |
+
*(np.array([1, 2, 3], dtype=dtype) for dtype in tm.ALL_INT_NUMPY_DTYPES),
|
507 |
+
# numpy floats
|
508 |
+
*(np.array([1.5, 2.5, 3.5], dtype=dtyp) for dtyp in tm.FLOAT_NUMPY_DTYPES),
|
509 |
+
# numpy object
|
510 |
+
np.array([1, "b", 3.5], dtype=object),
|
511 |
+
# pandas scalars
|
512 |
+
[Interval(1, 4), Interval(4, 6), Interval(6, 9)],
|
513 |
+
[Timestamp(2019, 1, 1), Timestamp(2019, 2, 1), Timestamp(2019, 3, 1)],
|
514 |
+
[Timedelta(1, "d"), Timedelta(2, "d"), Timedelta(3, "D")],
|
515 |
+
# pandas Integer arrays
|
516 |
+
*(pd.array([1, 2, 3], dtype=dtype) for dtype in tm.ALL_INT_EA_DTYPES),
|
517 |
+
# other pandas arrays
|
518 |
+
pd.IntervalIndex.from_breaks([1, 4, 6, 9]).array,
|
519 |
+
pd.date_range("2019-01-01", periods=3).array,
|
520 |
+
pd.timedelta_range(start="1d", periods=3).array,
|
521 |
+
],
|
522 |
+
)
|
523 |
+
def test_loc_getitem_with_non_string_categories(self, idx_values, ordered):
|
524 |
+
# GH-17569
|
525 |
+
cat_idx = CategoricalIndex(idx_values, ordered=ordered)
|
526 |
+
df = DataFrame({"A": ["foo", "bar", "baz"]}, index=cat_idx)
|
527 |
+
sl = slice(idx_values[0], idx_values[1])
|
528 |
+
|
529 |
+
# scalar selection
|
530 |
+
result = df.loc[idx_values[0]]
|
531 |
+
expected = Series(["foo"], index=["A"], name=idx_values[0])
|
532 |
+
tm.assert_series_equal(result, expected)
|
533 |
+
|
534 |
+
# list selection
|
535 |
+
result = df.loc[idx_values[:2]]
|
536 |
+
expected = DataFrame(["foo", "bar"], index=cat_idx[:2], columns=["A"])
|
537 |
+
tm.assert_frame_equal(result, expected)
|
538 |
+
|
539 |
+
# slice selection
|
540 |
+
result = df.loc[sl]
|
541 |
+
expected = DataFrame(["foo", "bar"], index=cat_idx[:2], columns=["A"])
|
542 |
+
tm.assert_frame_equal(result, expected)
|
543 |
+
|
544 |
+
# scalar assignment
|
545 |
+
result = df.copy()
|
546 |
+
result.loc[idx_values[0]] = "qux"
|
547 |
+
expected = DataFrame({"A": ["qux", "bar", "baz"]}, index=cat_idx)
|
548 |
+
tm.assert_frame_equal(result, expected)
|
549 |
+
|
550 |
+
# list assignment
|
551 |
+
result = df.copy()
|
552 |
+
result.loc[idx_values[:2], "A"] = ["qux", "qux2"]
|
553 |
+
expected = DataFrame({"A": ["qux", "qux2", "baz"]}, index=cat_idx)
|
554 |
+
tm.assert_frame_equal(result, expected)
|
555 |
+
|
556 |
+
# slice assignment
|
557 |
+
result = df.copy()
|
558 |
+
result.loc[sl, "A"] = ["qux", "qux2"]
|
559 |
+
expected = DataFrame({"A": ["qux", "qux2", "baz"]}, index=cat_idx)
|
560 |
+
tm.assert_frame_equal(result, expected)
|
561 |
+
|
562 |
+
def test_getitem_categorical_with_nan(self):
|
563 |
+
# GH#41933
|
564 |
+
ci = CategoricalIndex(["A", "B", np.nan])
|
565 |
+
|
566 |
+
ser = Series(range(3), index=ci)
|
567 |
+
|
568 |
+
assert ser[np.nan] == 2
|
569 |
+
assert ser.loc[np.nan] == 2
|
570 |
+
|
571 |
+
df = DataFrame(ser)
|
572 |
+
assert df.loc[np.nan, 0] == 2
|
573 |
+
assert df.loc[np.nan][0] == 2
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/test_chaining_and_caching.py
ADDED
@@ -0,0 +1,647 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from string import ascii_letters
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
import pytest
|
5 |
+
|
6 |
+
from pandas.errors import (
|
7 |
+
SettingWithCopyError,
|
8 |
+
SettingWithCopyWarning,
|
9 |
+
)
|
10 |
+
import pandas.util._test_decorators as td
|
11 |
+
|
12 |
+
import pandas as pd
|
13 |
+
from pandas import (
|
14 |
+
DataFrame,
|
15 |
+
Index,
|
16 |
+
Series,
|
17 |
+
Timestamp,
|
18 |
+
date_range,
|
19 |
+
option_context,
|
20 |
+
)
|
21 |
+
import pandas._testing as tm
|
22 |
+
|
23 |
+
msg = "A value is trying to be set on a copy of a slice from a DataFrame"
|
24 |
+
|
25 |
+
|
26 |
+
def random_text(nobs=100):
|
27 |
+
# Construct a DataFrame where each row is a random slice from 'letters'
|
28 |
+
idxs = np.random.default_rng(2).integers(len(ascii_letters), size=(nobs, 2))
|
29 |
+
idxs.sort(axis=1)
|
30 |
+
strings = [ascii_letters[x[0] : x[1]] for x in idxs]
|
31 |
+
|
32 |
+
return DataFrame(strings, columns=["letters"])
|
33 |
+
|
34 |
+
|
35 |
+
class TestCaching:
|
36 |
+
def test_slice_consolidate_invalidate_item_cache(self, using_copy_on_write):
|
37 |
+
# this is chained assignment, but will 'work'
|
38 |
+
with option_context("chained_assignment", None):
|
39 |
+
# #3970
|
40 |
+
df = DataFrame({"aa": np.arange(5), "bb": [2.2] * 5})
|
41 |
+
|
42 |
+
# Creates a second float block
|
43 |
+
df["cc"] = 0.0
|
44 |
+
|
45 |
+
# caches a reference to the 'bb' series
|
46 |
+
df["bb"]
|
47 |
+
|
48 |
+
# Assignment to wrong series
|
49 |
+
with tm.raises_chained_assignment_error():
|
50 |
+
df["bb"].iloc[0] = 0.17
|
51 |
+
df._clear_item_cache()
|
52 |
+
if not using_copy_on_write:
|
53 |
+
tm.assert_almost_equal(df["bb"][0], 0.17)
|
54 |
+
else:
|
55 |
+
# with ArrayManager, parent is not mutated with chained assignment
|
56 |
+
tm.assert_almost_equal(df["bb"][0], 2.2)
|
57 |
+
|
58 |
+
@pytest.mark.parametrize("do_ref", [True, False])
|
59 |
+
def test_setitem_cache_updating(self, do_ref):
|
60 |
+
# GH 5424
|
61 |
+
cont = ["one", "two", "three", "four", "five", "six", "seven"]
|
62 |
+
|
63 |
+
df = DataFrame({"a": cont, "b": cont[3:] + cont[:3], "c": np.arange(7)})
|
64 |
+
|
65 |
+
# ref the cache
|
66 |
+
if do_ref:
|
67 |
+
df.loc[0, "c"]
|
68 |
+
|
69 |
+
# set it
|
70 |
+
df.loc[7, "c"] = 1
|
71 |
+
|
72 |
+
assert df.loc[0, "c"] == 0.0
|
73 |
+
assert df.loc[7, "c"] == 1.0
|
74 |
+
|
75 |
+
def test_setitem_cache_updating_slices(
|
76 |
+
self, using_copy_on_write, warn_copy_on_write
|
77 |
+
):
|
78 |
+
# GH 7084
|
79 |
+
# not updating cache on series setting with slices
|
80 |
+
expected = DataFrame(
|
81 |
+
{"A": [600, 600, 600]}, index=date_range("5/7/2014", "5/9/2014")
|
82 |
+
)
|
83 |
+
out = DataFrame({"A": [0, 0, 0]}, index=date_range("5/7/2014", "5/9/2014"))
|
84 |
+
df = DataFrame({"C": ["A", "A", "A"], "D": [100, 200, 300]})
|
85 |
+
|
86 |
+
# loop through df to update out
|
87 |
+
six = Timestamp("5/7/2014")
|
88 |
+
eix = Timestamp("5/9/2014")
|
89 |
+
for ix, row in df.iterrows():
|
90 |
+
out.loc[six:eix, row["C"]] = out.loc[six:eix, row["C"]] + row["D"]
|
91 |
+
|
92 |
+
tm.assert_frame_equal(out, expected)
|
93 |
+
tm.assert_series_equal(out["A"], expected["A"])
|
94 |
+
|
95 |
+
# try via a chain indexing
|
96 |
+
# this actually works
|
97 |
+
out = DataFrame({"A": [0, 0, 0]}, index=date_range("5/7/2014", "5/9/2014"))
|
98 |
+
out_original = out.copy()
|
99 |
+
for ix, row in df.iterrows():
|
100 |
+
v = out[row["C"]][six:eix] + row["D"]
|
101 |
+
with tm.raises_chained_assignment_error(
|
102 |
+
(ix == 0) or warn_copy_on_write or using_copy_on_write
|
103 |
+
):
|
104 |
+
out[row["C"]][six:eix] = v
|
105 |
+
|
106 |
+
if not using_copy_on_write:
|
107 |
+
tm.assert_frame_equal(out, expected)
|
108 |
+
tm.assert_series_equal(out["A"], expected["A"])
|
109 |
+
else:
|
110 |
+
tm.assert_frame_equal(out, out_original)
|
111 |
+
tm.assert_series_equal(out["A"], out_original["A"])
|
112 |
+
|
113 |
+
out = DataFrame({"A": [0, 0, 0]}, index=date_range("5/7/2014", "5/9/2014"))
|
114 |
+
for ix, row in df.iterrows():
|
115 |
+
out.loc[six:eix, row["C"]] += row["D"]
|
116 |
+
|
117 |
+
tm.assert_frame_equal(out, expected)
|
118 |
+
tm.assert_series_equal(out["A"], expected["A"])
|
119 |
+
|
120 |
+
def test_altering_series_clears_parent_cache(
|
121 |
+
self, using_copy_on_write, warn_copy_on_write
|
122 |
+
):
|
123 |
+
# GH #33675
|
124 |
+
df = DataFrame([[1, 2], [3, 4]], index=["a", "b"], columns=["A", "B"])
|
125 |
+
ser = df["A"]
|
126 |
+
|
127 |
+
if using_copy_on_write or warn_copy_on_write:
|
128 |
+
assert "A" not in df._item_cache
|
129 |
+
else:
|
130 |
+
assert "A" in df._item_cache
|
131 |
+
|
132 |
+
# Adding a new entry to ser swaps in a new array, so "A" needs to
|
133 |
+
# be removed from df._item_cache
|
134 |
+
ser["c"] = 5
|
135 |
+
assert len(ser) == 3
|
136 |
+
assert "A" not in df._item_cache
|
137 |
+
assert df["A"] is not ser
|
138 |
+
assert len(df["A"]) == 2
|
139 |
+
|
140 |
+
|
141 |
+
class TestChaining:
|
142 |
+
def test_setitem_chained_setfault(self, using_copy_on_write):
|
143 |
+
# GH6026
|
144 |
+
data = ["right", "left", "left", "left", "right", "left", "timeout"]
|
145 |
+
mdata = ["right", "left", "left", "left", "right", "left", "none"]
|
146 |
+
|
147 |
+
df = DataFrame({"response": np.array(data)})
|
148 |
+
mask = df.response == "timeout"
|
149 |
+
with tm.raises_chained_assignment_error():
|
150 |
+
df.response[mask] = "none"
|
151 |
+
if using_copy_on_write:
|
152 |
+
tm.assert_frame_equal(df, DataFrame({"response": data}))
|
153 |
+
else:
|
154 |
+
tm.assert_frame_equal(df, DataFrame({"response": mdata}))
|
155 |
+
|
156 |
+
recarray = np.rec.fromarrays([data], names=["response"])
|
157 |
+
df = DataFrame(recarray)
|
158 |
+
mask = df.response == "timeout"
|
159 |
+
with tm.raises_chained_assignment_error():
|
160 |
+
df.response[mask] = "none"
|
161 |
+
if using_copy_on_write:
|
162 |
+
tm.assert_frame_equal(df, DataFrame({"response": data}))
|
163 |
+
else:
|
164 |
+
tm.assert_frame_equal(df, DataFrame({"response": mdata}))
|
165 |
+
|
166 |
+
df = DataFrame({"response": data, "response1": data})
|
167 |
+
df_original = df.copy()
|
168 |
+
mask = df.response == "timeout"
|
169 |
+
with tm.raises_chained_assignment_error():
|
170 |
+
df.response[mask] = "none"
|
171 |
+
if using_copy_on_write:
|
172 |
+
tm.assert_frame_equal(df, df_original)
|
173 |
+
else:
|
174 |
+
tm.assert_frame_equal(df, DataFrame({"response": mdata, "response1": data}))
|
175 |
+
|
176 |
+
# GH 6056
|
177 |
+
expected = DataFrame({"A": [np.nan, "bar", "bah", "foo", "bar"]})
|
178 |
+
df = DataFrame({"A": np.array(["foo", "bar", "bah", "foo", "bar"])})
|
179 |
+
with tm.raises_chained_assignment_error():
|
180 |
+
df["A"].iloc[0] = np.nan
|
181 |
+
if using_copy_on_write:
|
182 |
+
expected = DataFrame({"A": ["foo", "bar", "bah", "foo", "bar"]})
|
183 |
+
else:
|
184 |
+
expected = DataFrame({"A": [np.nan, "bar", "bah", "foo", "bar"]})
|
185 |
+
result = df.head()
|
186 |
+
tm.assert_frame_equal(result, expected)
|
187 |
+
|
188 |
+
df = DataFrame({"A": np.array(["foo", "bar", "bah", "foo", "bar"])})
|
189 |
+
with tm.raises_chained_assignment_error():
|
190 |
+
df.A.iloc[0] = np.nan
|
191 |
+
result = df.head()
|
192 |
+
tm.assert_frame_equal(result, expected)
|
193 |
+
|
194 |
+
@pytest.mark.arm_slow
|
195 |
+
def test_detect_chained_assignment(self, using_copy_on_write):
|
196 |
+
with option_context("chained_assignment", "raise"):
|
197 |
+
# work with the chain
|
198 |
+
expected = DataFrame([[-5, 1], [-6, 3]], columns=list("AB"))
|
199 |
+
df = DataFrame(
|
200 |
+
np.arange(4).reshape(2, 2), columns=list("AB"), dtype="int64"
|
201 |
+
)
|
202 |
+
df_original = df.copy()
|
203 |
+
assert df._is_copy is None
|
204 |
+
|
205 |
+
with tm.raises_chained_assignment_error():
|
206 |
+
df["A"][0] = -5
|
207 |
+
with tm.raises_chained_assignment_error():
|
208 |
+
df["A"][1] = -6
|
209 |
+
if using_copy_on_write:
|
210 |
+
tm.assert_frame_equal(df, df_original)
|
211 |
+
else:
|
212 |
+
tm.assert_frame_equal(df, expected)
|
213 |
+
|
214 |
+
@pytest.mark.arm_slow
|
215 |
+
def test_detect_chained_assignment_raises(
|
216 |
+
self, using_array_manager, using_copy_on_write, warn_copy_on_write
|
217 |
+
):
|
218 |
+
# test with the chaining
|
219 |
+
df = DataFrame(
|
220 |
+
{
|
221 |
+
"A": Series(range(2), dtype="int64"),
|
222 |
+
"B": np.array(np.arange(2, 4), dtype=np.float64),
|
223 |
+
}
|
224 |
+
)
|
225 |
+
df_original = df.copy()
|
226 |
+
assert df._is_copy is None
|
227 |
+
|
228 |
+
if using_copy_on_write:
|
229 |
+
with tm.raises_chained_assignment_error():
|
230 |
+
df["A"][0] = -5
|
231 |
+
with tm.raises_chained_assignment_error():
|
232 |
+
df["A"][1] = -6
|
233 |
+
tm.assert_frame_equal(df, df_original)
|
234 |
+
elif warn_copy_on_write:
|
235 |
+
with tm.raises_chained_assignment_error():
|
236 |
+
df["A"][0] = -5
|
237 |
+
with tm.raises_chained_assignment_error():
|
238 |
+
df["A"][1] = np.nan
|
239 |
+
elif not using_array_manager:
|
240 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
241 |
+
with tm.raises_chained_assignment_error():
|
242 |
+
df["A"][0] = -5
|
243 |
+
|
244 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
245 |
+
with tm.raises_chained_assignment_error():
|
246 |
+
df["A"][1] = np.nan
|
247 |
+
|
248 |
+
assert df["A"]._is_copy is None
|
249 |
+
else:
|
250 |
+
# INFO(ArrayManager) for ArrayManager it doesn't matter that it's
|
251 |
+
# a mixed dataframe
|
252 |
+
df["A"][0] = -5
|
253 |
+
df["A"][1] = -6
|
254 |
+
expected = DataFrame([[-5, 2], [-6, 3]], columns=list("AB"))
|
255 |
+
expected["B"] = expected["B"].astype("float64")
|
256 |
+
tm.assert_frame_equal(df, expected)
|
257 |
+
|
258 |
+
@pytest.mark.arm_slow
|
259 |
+
def test_detect_chained_assignment_fails(
|
260 |
+
self, using_copy_on_write, warn_copy_on_write
|
261 |
+
):
|
262 |
+
# Using a copy (the chain), fails
|
263 |
+
df = DataFrame(
|
264 |
+
{
|
265 |
+
"A": Series(range(2), dtype="int64"),
|
266 |
+
"B": np.array(np.arange(2, 4), dtype=np.float64),
|
267 |
+
}
|
268 |
+
)
|
269 |
+
|
270 |
+
if using_copy_on_write or warn_copy_on_write:
|
271 |
+
with tm.raises_chained_assignment_error():
|
272 |
+
df.loc[0]["A"] = -5
|
273 |
+
else:
|
274 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
275 |
+
df.loc[0]["A"] = -5
|
276 |
+
|
277 |
+
@pytest.mark.arm_slow
|
278 |
+
def test_detect_chained_assignment_doc_example(
|
279 |
+
self, using_copy_on_write, warn_copy_on_write
|
280 |
+
):
|
281 |
+
# Doc example
|
282 |
+
df = DataFrame(
|
283 |
+
{
|
284 |
+
"a": ["one", "one", "two", "three", "two", "one", "six"],
|
285 |
+
"c": Series(range(7), dtype="int64"),
|
286 |
+
}
|
287 |
+
)
|
288 |
+
assert df._is_copy is None
|
289 |
+
|
290 |
+
indexer = df.a.str.startswith("o")
|
291 |
+
if using_copy_on_write or warn_copy_on_write:
|
292 |
+
with tm.raises_chained_assignment_error():
|
293 |
+
df[indexer]["c"] = 42
|
294 |
+
else:
|
295 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
296 |
+
df[indexer]["c"] = 42
|
297 |
+
|
298 |
+
@pytest.mark.arm_slow
|
299 |
+
def test_detect_chained_assignment_object_dtype(
|
300 |
+
self, using_array_manager, using_copy_on_write, warn_copy_on_write
|
301 |
+
):
|
302 |
+
expected = DataFrame({"A": [111, "bbb", "ccc"], "B": [1, 2, 3]})
|
303 |
+
df = DataFrame(
|
304 |
+
{"A": Series(["aaa", "bbb", "ccc"], dtype=object), "B": [1, 2, 3]}
|
305 |
+
)
|
306 |
+
df_original = df.copy()
|
307 |
+
|
308 |
+
if not using_copy_on_write and not warn_copy_on_write:
|
309 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
310 |
+
df.loc[0]["A"] = 111
|
311 |
+
|
312 |
+
if using_copy_on_write:
|
313 |
+
with tm.raises_chained_assignment_error():
|
314 |
+
df["A"][0] = 111
|
315 |
+
tm.assert_frame_equal(df, df_original)
|
316 |
+
elif warn_copy_on_write:
|
317 |
+
with tm.raises_chained_assignment_error():
|
318 |
+
df["A"][0] = 111
|
319 |
+
tm.assert_frame_equal(df, expected)
|
320 |
+
elif not using_array_manager:
|
321 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
322 |
+
with tm.raises_chained_assignment_error():
|
323 |
+
df["A"][0] = 111
|
324 |
+
|
325 |
+
df.loc[0, "A"] = 111
|
326 |
+
tm.assert_frame_equal(df, expected)
|
327 |
+
else:
|
328 |
+
# INFO(ArrayManager) for ArrayManager it doesn't matter that it's
|
329 |
+
# a mixed dataframe
|
330 |
+
df["A"][0] = 111
|
331 |
+
tm.assert_frame_equal(df, expected)
|
332 |
+
|
333 |
+
@pytest.mark.arm_slow
|
334 |
+
def test_detect_chained_assignment_is_copy_pickle(self):
|
335 |
+
# gh-5475: Make sure that is_copy is picked up reconstruction
|
336 |
+
df = DataFrame({"A": [1, 2]})
|
337 |
+
assert df._is_copy is None
|
338 |
+
|
339 |
+
with tm.ensure_clean("__tmp__pickle") as path:
|
340 |
+
df.to_pickle(path)
|
341 |
+
df2 = pd.read_pickle(path)
|
342 |
+
df2["B"] = df2["A"]
|
343 |
+
df2["B"] = df2["A"]
|
344 |
+
|
345 |
+
@pytest.mark.arm_slow
|
346 |
+
def test_detect_chained_assignment_setting_entire_column(self):
|
347 |
+
# gh-5597: a spurious raise as we are setting the entire column here
|
348 |
+
|
349 |
+
df = random_text(100000)
|
350 |
+
|
351 |
+
# Always a copy
|
352 |
+
x = df.iloc[[0, 1, 2]]
|
353 |
+
assert x._is_copy is not None
|
354 |
+
|
355 |
+
x = df.iloc[[0, 1, 2, 4]]
|
356 |
+
assert x._is_copy is not None
|
357 |
+
|
358 |
+
# Explicitly copy
|
359 |
+
indexer = df.letters.apply(lambda x: len(x) > 10)
|
360 |
+
df = df.loc[indexer].copy()
|
361 |
+
|
362 |
+
assert df._is_copy is None
|
363 |
+
df["letters"] = df["letters"].apply(str.lower)
|
364 |
+
|
365 |
+
@pytest.mark.arm_slow
|
366 |
+
def test_detect_chained_assignment_implicit_take(self):
|
367 |
+
# Implicitly take
|
368 |
+
df = random_text(100000)
|
369 |
+
indexer = df.letters.apply(lambda x: len(x) > 10)
|
370 |
+
df = df.loc[indexer]
|
371 |
+
|
372 |
+
assert df._is_copy is not None
|
373 |
+
df["letters"] = df["letters"].apply(str.lower)
|
374 |
+
|
375 |
+
@pytest.mark.arm_slow
|
376 |
+
def test_detect_chained_assignment_implicit_take2(
|
377 |
+
self, using_copy_on_write, warn_copy_on_write
|
378 |
+
):
|
379 |
+
if using_copy_on_write or warn_copy_on_write:
|
380 |
+
pytest.skip("_is_copy is not always set for CoW")
|
381 |
+
# Implicitly take 2
|
382 |
+
df = random_text(100000)
|
383 |
+
indexer = df.letters.apply(lambda x: len(x) > 10)
|
384 |
+
|
385 |
+
df = df.loc[indexer]
|
386 |
+
assert df._is_copy is not None
|
387 |
+
df.loc[:, "letters"] = df["letters"].apply(str.lower)
|
388 |
+
|
389 |
+
# with the enforcement of #45333 in 2.0, the .loc[:, letters] setting
|
390 |
+
# is inplace, so df._is_copy remains non-None.
|
391 |
+
assert df._is_copy is not None
|
392 |
+
|
393 |
+
df["letters"] = df["letters"].apply(str.lower)
|
394 |
+
assert df._is_copy is None
|
395 |
+
|
396 |
+
@pytest.mark.arm_slow
|
397 |
+
def test_detect_chained_assignment_str(self):
|
398 |
+
df = random_text(100000)
|
399 |
+
indexer = df.letters.apply(lambda x: len(x) > 10)
|
400 |
+
df.loc[indexer, "letters"] = df.loc[indexer, "letters"].apply(str.lower)
|
401 |
+
|
402 |
+
@pytest.mark.arm_slow
|
403 |
+
def test_detect_chained_assignment_is_copy(self):
|
404 |
+
# an identical take, so no copy
|
405 |
+
df = DataFrame({"a": [1]}).dropna()
|
406 |
+
assert df._is_copy is None
|
407 |
+
df["a"] += 1
|
408 |
+
|
409 |
+
@pytest.mark.arm_slow
|
410 |
+
def test_detect_chained_assignment_sorting(self):
|
411 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)))
|
412 |
+
ser = df.iloc[:, 0].sort_values()
|
413 |
+
|
414 |
+
tm.assert_series_equal(ser, df.iloc[:, 0].sort_values())
|
415 |
+
tm.assert_series_equal(ser, df[0].sort_values())
|
416 |
+
|
417 |
+
@pytest.mark.arm_slow
|
418 |
+
def test_detect_chained_assignment_false_positives(self):
|
419 |
+
# see gh-6025: false positives
|
420 |
+
df = DataFrame({"column1": ["a", "a", "a"], "column2": [4, 8, 9]})
|
421 |
+
str(df)
|
422 |
+
|
423 |
+
df["column1"] = df["column1"] + "b"
|
424 |
+
str(df)
|
425 |
+
|
426 |
+
df = df[df["column2"] != 8]
|
427 |
+
str(df)
|
428 |
+
|
429 |
+
df["column1"] = df["column1"] + "c"
|
430 |
+
str(df)
|
431 |
+
|
432 |
+
@pytest.mark.arm_slow
|
433 |
+
def test_detect_chained_assignment_undefined_column(
|
434 |
+
self, using_copy_on_write, warn_copy_on_write
|
435 |
+
):
|
436 |
+
# from SO:
|
437 |
+
# https://stackoverflow.com/questions/24054495/potential-bug-setting-value-for-undefined-column-using-iloc
|
438 |
+
df = DataFrame(np.arange(0, 9), columns=["count"])
|
439 |
+
df["group"] = "b"
|
440 |
+
df_original = df.copy()
|
441 |
+
|
442 |
+
if using_copy_on_write:
|
443 |
+
with tm.raises_chained_assignment_error():
|
444 |
+
df.iloc[0:5]["group"] = "a"
|
445 |
+
tm.assert_frame_equal(df, df_original)
|
446 |
+
elif warn_copy_on_write:
|
447 |
+
with tm.raises_chained_assignment_error():
|
448 |
+
df.iloc[0:5]["group"] = "a"
|
449 |
+
else:
|
450 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
451 |
+
with tm.raises_chained_assignment_error():
|
452 |
+
df.iloc[0:5]["group"] = "a"
|
453 |
+
|
454 |
+
@pytest.mark.arm_slow
|
455 |
+
def test_detect_chained_assignment_changing_dtype(
|
456 |
+
self, using_array_manager, using_copy_on_write, warn_copy_on_write
|
457 |
+
):
|
458 |
+
# Mixed type setting but same dtype & changing dtype
|
459 |
+
df = DataFrame(
|
460 |
+
{
|
461 |
+
"A": date_range("20130101", periods=5),
|
462 |
+
"B": np.random.default_rng(2).standard_normal(5),
|
463 |
+
"C": np.arange(5, dtype="int64"),
|
464 |
+
"D": ["a", "b", "c", "d", "e"],
|
465 |
+
}
|
466 |
+
)
|
467 |
+
df_original = df.copy()
|
468 |
+
|
469 |
+
if using_copy_on_write or warn_copy_on_write:
|
470 |
+
with tm.raises_chained_assignment_error():
|
471 |
+
df.loc[2]["D"] = "foo"
|
472 |
+
with tm.raises_chained_assignment_error():
|
473 |
+
df.loc[2]["C"] = "foo"
|
474 |
+
tm.assert_frame_equal(df, df_original)
|
475 |
+
with tm.raises_chained_assignment_error(extra_warnings=(FutureWarning,)):
|
476 |
+
df["C"][2] = "foo"
|
477 |
+
if using_copy_on_write:
|
478 |
+
tm.assert_frame_equal(df, df_original)
|
479 |
+
else:
|
480 |
+
assert df.loc[2, "C"] == "foo"
|
481 |
+
else:
|
482 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
483 |
+
df.loc[2]["D"] = "foo"
|
484 |
+
|
485 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
486 |
+
df.loc[2]["C"] = "foo"
|
487 |
+
|
488 |
+
if not using_array_manager:
|
489 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
490 |
+
with tm.raises_chained_assignment_error():
|
491 |
+
df["C"][2] = "foo"
|
492 |
+
else:
|
493 |
+
# INFO(ArrayManager) for ArrayManager it doesn't matter if it's
|
494 |
+
# changing the dtype or not
|
495 |
+
df["C"][2] = "foo"
|
496 |
+
assert df.loc[2, "C"] == "foo"
|
497 |
+
|
498 |
+
def test_setting_with_copy_bug(self, using_copy_on_write, warn_copy_on_write):
|
499 |
+
# operating on a copy
|
500 |
+
df = DataFrame(
|
501 |
+
{"a": list(range(4)), "b": list("ab.."), "c": ["a", "b", np.nan, "d"]}
|
502 |
+
)
|
503 |
+
df_original = df.copy()
|
504 |
+
mask = pd.isna(df.c)
|
505 |
+
|
506 |
+
if using_copy_on_write:
|
507 |
+
with tm.raises_chained_assignment_error():
|
508 |
+
df[["c"]][mask] = df[["b"]][mask]
|
509 |
+
tm.assert_frame_equal(df, df_original)
|
510 |
+
elif warn_copy_on_write:
|
511 |
+
with tm.raises_chained_assignment_error():
|
512 |
+
df[["c"]][mask] = df[["b"]][mask]
|
513 |
+
else:
|
514 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
515 |
+
df[["c"]][mask] = df[["b"]][mask]
|
516 |
+
|
517 |
+
def test_setting_with_copy_bug_no_warning(self):
|
518 |
+
# invalid warning as we are returning a new object
|
519 |
+
# GH 8730
|
520 |
+
df1 = DataFrame({"x": Series(["a", "b", "c"]), "y": Series(["d", "e", "f"])})
|
521 |
+
df2 = df1[["x"]]
|
522 |
+
|
523 |
+
# this should not raise
|
524 |
+
df2["y"] = ["g", "h", "i"]
|
525 |
+
|
526 |
+
def test_detect_chained_assignment_warnings_errors(
|
527 |
+
self, using_copy_on_write, warn_copy_on_write
|
528 |
+
):
|
529 |
+
df = DataFrame({"A": ["aaa", "bbb", "ccc"], "B": [1, 2, 3]})
|
530 |
+
if using_copy_on_write or warn_copy_on_write:
|
531 |
+
with tm.raises_chained_assignment_error():
|
532 |
+
df.loc[0]["A"] = 111
|
533 |
+
return
|
534 |
+
|
535 |
+
with option_context("chained_assignment", "warn"):
|
536 |
+
with tm.assert_produces_warning(SettingWithCopyWarning):
|
537 |
+
df.loc[0]["A"] = 111
|
538 |
+
|
539 |
+
with option_context("chained_assignment", "raise"):
|
540 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
541 |
+
df.loc[0]["A"] = 111
|
542 |
+
|
543 |
+
@pytest.mark.parametrize("rhs", [3, DataFrame({0: [1, 2, 3, 4]})])
|
544 |
+
def test_detect_chained_assignment_warning_stacklevel(
|
545 |
+
self, rhs, using_copy_on_write, warn_copy_on_write
|
546 |
+
):
|
547 |
+
# GH#42570
|
548 |
+
df = DataFrame(np.arange(25).reshape(5, 5))
|
549 |
+
df_original = df.copy()
|
550 |
+
chained = df.loc[:3]
|
551 |
+
with option_context("chained_assignment", "warn"):
|
552 |
+
if not using_copy_on_write and not warn_copy_on_write:
|
553 |
+
with tm.assert_produces_warning(SettingWithCopyWarning) as t:
|
554 |
+
chained[2] = rhs
|
555 |
+
assert t[0].filename == __file__
|
556 |
+
else:
|
557 |
+
# INFO(CoW) no warning, and original dataframe not changed
|
558 |
+
chained[2] = rhs
|
559 |
+
tm.assert_frame_equal(df, df_original)
|
560 |
+
|
561 |
+
# TODO(ArrayManager) fast_xs with array-like scalars is not yet working
|
562 |
+
@td.skip_array_manager_not_yet_implemented
|
563 |
+
def test_chained_getitem_with_lists(self):
|
564 |
+
# GH6394
|
565 |
+
# Regression in chained getitem indexing with embedded list-like from
|
566 |
+
# 0.12
|
567 |
+
|
568 |
+
df = DataFrame({"A": 5 * [np.zeros(3)], "B": 5 * [np.ones(3)]})
|
569 |
+
expected = df["A"].iloc[2]
|
570 |
+
result = df.loc[2, "A"]
|
571 |
+
tm.assert_numpy_array_equal(result, expected)
|
572 |
+
result2 = df.iloc[2]["A"]
|
573 |
+
tm.assert_numpy_array_equal(result2, expected)
|
574 |
+
result3 = df["A"].loc[2]
|
575 |
+
tm.assert_numpy_array_equal(result3, expected)
|
576 |
+
result4 = df["A"].iloc[2]
|
577 |
+
tm.assert_numpy_array_equal(result4, expected)
|
578 |
+
|
579 |
+
def test_cache_updating(self):
|
580 |
+
# GH 4939, make sure to update the cache on setitem
|
581 |
+
|
582 |
+
df = DataFrame(
|
583 |
+
np.zeros((10, 4)),
|
584 |
+
columns=Index(list("ABCD"), dtype=object),
|
585 |
+
)
|
586 |
+
df["A"] # cache series
|
587 |
+
df.loc["Hello Friend"] = df.iloc[0]
|
588 |
+
assert "Hello Friend" in df["A"].index
|
589 |
+
assert "Hello Friend" in df["B"].index
|
590 |
+
|
591 |
+
def test_cache_updating2(self, using_copy_on_write):
|
592 |
+
# 10264
|
593 |
+
df = DataFrame(
|
594 |
+
np.zeros((5, 5), dtype="int64"),
|
595 |
+
columns=["a", "b", "c", "d", "e"],
|
596 |
+
index=range(5),
|
597 |
+
)
|
598 |
+
df["f"] = 0
|
599 |
+
df_orig = df.copy()
|
600 |
+
if using_copy_on_write:
|
601 |
+
with pytest.raises(ValueError, match="read-only"):
|
602 |
+
df.f.values[3] = 1
|
603 |
+
tm.assert_frame_equal(df, df_orig)
|
604 |
+
return
|
605 |
+
|
606 |
+
df.f.values[3] = 1
|
607 |
+
|
608 |
+
df.f.values[3] = 2
|
609 |
+
expected = DataFrame(
|
610 |
+
np.zeros((5, 6), dtype="int64"),
|
611 |
+
columns=["a", "b", "c", "d", "e", "f"],
|
612 |
+
index=range(5),
|
613 |
+
)
|
614 |
+
expected.at[3, "f"] = 2
|
615 |
+
tm.assert_frame_equal(df, expected)
|
616 |
+
expected = Series([0, 0, 0, 2, 0], name="f")
|
617 |
+
tm.assert_series_equal(df.f, expected)
|
618 |
+
|
619 |
+
def test_iloc_setitem_chained_assignment(self, using_copy_on_write):
|
620 |
+
# GH#3970
|
621 |
+
with option_context("chained_assignment", None):
|
622 |
+
df = DataFrame({"aa": range(5), "bb": [2.2] * 5})
|
623 |
+
df["cc"] = 0.0
|
624 |
+
|
625 |
+
ck = [True] * len(df)
|
626 |
+
|
627 |
+
with tm.raises_chained_assignment_error():
|
628 |
+
df["bb"].iloc[0] = 0.13
|
629 |
+
|
630 |
+
# GH#3970 this lookup used to break the chained setting to 0.15
|
631 |
+
df.iloc[ck]
|
632 |
+
|
633 |
+
with tm.raises_chained_assignment_error():
|
634 |
+
df["bb"].iloc[0] = 0.15
|
635 |
+
|
636 |
+
if not using_copy_on_write:
|
637 |
+
assert df["bb"].iloc[0] == 0.15
|
638 |
+
else:
|
639 |
+
assert df["bb"].iloc[0] == 2.2
|
640 |
+
|
641 |
+
def test_getitem_loc_assignment_slice_state(self):
|
642 |
+
# GH 13569
|
643 |
+
df = DataFrame({"a": [10, 20, 30]})
|
644 |
+
with tm.raises_chained_assignment_error():
|
645 |
+
df["a"].loc[4] = 40
|
646 |
+
tm.assert_frame_equal(df, DataFrame({"a": [10, 20, 30]}))
|
647 |
+
tm.assert_series_equal(df["a"], Series([10, 20, 30], name="a"))
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/test_check_indexer.py
ADDED
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
import pandas as pd
|
5 |
+
import pandas._testing as tm
|
6 |
+
from pandas.api.indexers import check_array_indexer
|
7 |
+
|
8 |
+
|
9 |
+
@pytest.mark.parametrize(
|
10 |
+
"indexer, expected",
|
11 |
+
[
|
12 |
+
# integer
|
13 |
+
([1, 2], np.array([1, 2], dtype=np.intp)),
|
14 |
+
(np.array([1, 2], dtype="int64"), np.array([1, 2], dtype=np.intp)),
|
15 |
+
(pd.array([1, 2], dtype="Int32"), np.array([1, 2], dtype=np.intp)),
|
16 |
+
(pd.Index([1, 2]), np.array([1, 2], dtype=np.intp)),
|
17 |
+
# boolean
|
18 |
+
([True, False, True], np.array([True, False, True], dtype=np.bool_)),
|
19 |
+
(np.array([True, False, True]), np.array([True, False, True], dtype=np.bool_)),
|
20 |
+
(
|
21 |
+
pd.array([True, False, True], dtype="boolean"),
|
22 |
+
np.array([True, False, True], dtype=np.bool_),
|
23 |
+
),
|
24 |
+
# other
|
25 |
+
([], np.array([], dtype=np.intp)),
|
26 |
+
],
|
27 |
+
)
|
28 |
+
def test_valid_input(indexer, expected):
|
29 |
+
arr = np.array([1, 2, 3])
|
30 |
+
result = check_array_indexer(arr, indexer)
|
31 |
+
tm.assert_numpy_array_equal(result, expected)
|
32 |
+
|
33 |
+
|
34 |
+
@pytest.mark.parametrize(
|
35 |
+
"indexer", [[True, False, None], pd.array([True, False, None], dtype="boolean")]
|
36 |
+
)
|
37 |
+
def test_boolean_na_returns_indexer(indexer):
|
38 |
+
# https://github.com/pandas-dev/pandas/issues/31503
|
39 |
+
arr = np.array([1, 2, 3])
|
40 |
+
|
41 |
+
result = check_array_indexer(arr, indexer)
|
42 |
+
expected = np.array([True, False, False], dtype=bool)
|
43 |
+
|
44 |
+
tm.assert_numpy_array_equal(result, expected)
|
45 |
+
|
46 |
+
|
47 |
+
@pytest.mark.parametrize(
|
48 |
+
"indexer",
|
49 |
+
[
|
50 |
+
[True, False],
|
51 |
+
pd.array([True, False], dtype="boolean"),
|
52 |
+
np.array([True, False], dtype=np.bool_),
|
53 |
+
],
|
54 |
+
)
|
55 |
+
def test_bool_raise_length(indexer):
|
56 |
+
arr = np.array([1, 2, 3])
|
57 |
+
|
58 |
+
msg = "Boolean index has wrong length"
|
59 |
+
with pytest.raises(IndexError, match=msg):
|
60 |
+
check_array_indexer(arr, indexer)
|
61 |
+
|
62 |
+
|
63 |
+
@pytest.mark.parametrize(
|
64 |
+
"indexer", [[0, 1, None], pd.array([0, 1, pd.NA], dtype="Int64")]
|
65 |
+
)
|
66 |
+
def test_int_raise_missing_values(indexer):
|
67 |
+
arr = np.array([1, 2, 3])
|
68 |
+
|
69 |
+
msg = "Cannot index with an integer indexer containing NA values"
|
70 |
+
with pytest.raises(ValueError, match=msg):
|
71 |
+
check_array_indexer(arr, indexer)
|
72 |
+
|
73 |
+
|
74 |
+
@pytest.mark.parametrize(
|
75 |
+
"indexer",
|
76 |
+
[
|
77 |
+
[0.0, 1.0],
|
78 |
+
np.array([1.0, 2.0], dtype="float64"),
|
79 |
+
np.array([True, False], dtype=object),
|
80 |
+
pd.Index([True, False], dtype=object),
|
81 |
+
],
|
82 |
+
)
|
83 |
+
def test_raise_invalid_array_dtypes(indexer):
|
84 |
+
arr = np.array([1, 2, 3])
|
85 |
+
|
86 |
+
msg = "arrays used as indices must be of integer or boolean type"
|
87 |
+
with pytest.raises(IndexError, match=msg):
|
88 |
+
check_array_indexer(arr, indexer)
|
89 |
+
|
90 |
+
|
91 |
+
def test_raise_nullable_string_dtype(nullable_string_dtype):
|
92 |
+
indexer = pd.array(["a", "b"], dtype=nullable_string_dtype)
|
93 |
+
arr = np.array([1, 2, 3])
|
94 |
+
|
95 |
+
msg = "arrays used as indices must be of integer or boolean type"
|
96 |
+
with pytest.raises(IndexError, match=msg):
|
97 |
+
check_array_indexer(arr, indexer)
|
98 |
+
|
99 |
+
|
100 |
+
@pytest.mark.parametrize("indexer", [None, Ellipsis, slice(0, 3), (None,)])
|
101 |
+
def test_pass_through_non_array_likes(indexer):
|
102 |
+
arr = np.array([1, 2, 3])
|
103 |
+
|
104 |
+
result = check_array_indexer(arr, indexer)
|
105 |
+
assert result == indexer
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/test_coercion.py
ADDED
@@ -0,0 +1,940 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
from datetime import (
|
4 |
+
datetime,
|
5 |
+
timedelta,
|
6 |
+
)
|
7 |
+
import itertools
|
8 |
+
|
9 |
+
import numpy as np
|
10 |
+
import pytest
|
11 |
+
|
12 |
+
from pandas._config import using_pyarrow_string_dtype
|
13 |
+
|
14 |
+
from pandas.compat import (
|
15 |
+
IS64,
|
16 |
+
is_platform_windows,
|
17 |
+
)
|
18 |
+
from pandas.compat.numpy import np_version_gt2
|
19 |
+
|
20 |
+
import pandas as pd
|
21 |
+
import pandas._testing as tm
|
22 |
+
|
23 |
+
###############################################################
|
24 |
+
# Index / Series common tests which may trigger dtype coercions
|
25 |
+
###############################################################
|
26 |
+
|
27 |
+
|
28 |
+
@pytest.fixture(autouse=True, scope="class")
|
29 |
+
def check_comprehensiveness(request):
|
30 |
+
# Iterate over combination of dtype, method and klass
|
31 |
+
# and ensure that each are contained within a collected test
|
32 |
+
cls = request.cls
|
33 |
+
combos = itertools.product(cls.klasses, cls.dtypes, [cls.method])
|
34 |
+
|
35 |
+
def has_test(combo):
|
36 |
+
klass, dtype, method = combo
|
37 |
+
cls_funcs = request.node.session.items
|
38 |
+
return any(
|
39 |
+
klass in x.name and dtype in x.name and method in x.name for x in cls_funcs
|
40 |
+
)
|
41 |
+
|
42 |
+
opts = request.config.option
|
43 |
+
if opts.lf or opts.keyword:
|
44 |
+
# If we are running with "last-failed" or -k foo, we expect to only
|
45 |
+
# run a subset of tests.
|
46 |
+
yield
|
47 |
+
|
48 |
+
else:
|
49 |
+
for combo in combos:
|
50 |
+
if not has_test(combo):
|
51 |
+
raise AssertionError(
|
52 |
+
f"test method is not defined: {cls.__name__}, {combo}"
|
53 |
+
)
|
54 |
+
|
55 |
+
yield
|
56 |
+
|
57 |
+
|
58 |
+
class CoercionBase:
|
59 |
+
klasses = ["index", "series"]
|
60 |
+
dtypes = [
|
61 |
+
"object",
|
62 |
+
"int64",
|
63 |
+
"float64",
|
64 |
+
"complex128",
|
65 |
+
"bool",
|
66 |
+
"datetime64",
|
67 |
+
"datetime64tz",
|
68 |
+
"timedelta64",
|
69 |
+
"period",
|
70 |
+
]
|
71 |
+
|
72 |
+
@property
|
73 |
+
def method(self):
|
74 |
+
raise NotImplementedError(self)
|
75 |
+
|
76 |
+
|
77 |
+
class TestSetitemCoercion(CoercionBase):
|
78 |
+
method = "setitem"
|
79 |
+
|
80 |
+
# disable comprehensiveness tests, as most of these have been moved to
|
81 |
+
# tests.series.indexing.test_setitem in SetitemCastingEquivalents subclasses.
|
82 |
+
klasses: list[str] = []
|
83 |
+
|
84 |
+
def test_setitem_series_no_coercion_from_values_list(self):
|
85 |
+
# GH35865 - int casted to str when internally calling np.array(ser.values)
|
86 |
+
ser = pd.Series(["a", 1])
|
87 |
+
ser[:] = list(ser.values)
|
88 |
+
|
89 |
+
expected = pd.Series(["a", 1])
|
90 |
+
|
91 |
+
tm.assert_series_equal(ser, expected)
|
92 |
+
|
93 |
+
def _assert_setitem_index_conversion(
|
94 |
+
self, original_series, loc_key, expected_index, expected_dtype
|
95 |
+
):
|
96 |
+
"""test index's coercion triggered by assign key"""
|
97 |
+
temp = original_series.copy()
|
98 |
+
# GH#33469 pre-2.0 with int loc_key and temp.index.dtype == np.float64
|
99 |
+
# `temp[loc_key] = 5` treated loc_key as positional
|
100 |
+
temp[loc_key] = 5
|
101 |
+
exp = pd.Series([1, 2, 3, 4, 5], index=expected_index)
|
102 |
+
tm.assert_series_equal(temp, exp)
|
103 |
+
# check dtype explicitly for sure
|
104 |
+
assert temp.index.dtype == expected_dtype
|
105 |
+
|
106 |
+
temp = original_series.copy()
|
107 |
+
temp.loc[loc_key] = 5
|
108 |
+
exp = pd.Series([1, 2, 3, 4, 5], index=expected_index)
|
109 |
+
tm.assert_series_equal(temp, exp)
|
110 |
+
# check dtype explicitly for sure
|
111 |
+
assert temp.index.dtype == expected_dtype
|
112 |
+
|
113 |
+
@pytest.mark.parametrize(
|
114 |
+
"val,exp_dtype", [("x", object), (5, IndexError), (1.1, object)]
|
115 |
+
)
|
116 |
+
def test_setitem_index_object(self, val, exp_dtype):
|
117 |
+
obj = pd.Series([1, 2, 3, 4], index=pd.Index(list("abcd"), dtype=object))
|
118 |
+
assert obj.index.dtype == object
|
119 |
+
|
120 |
+
if exp_dtype is IndexError:
|
121 |
+
temp = obj.copy()
|
122 |
+
warn_msg = "Series.__setitem__ treating keys as positions is deprecated"
|
123 |
+
msg = "index 5 is out of bounds for axis 0 with size 4"
|
124 |
+
with pytest.raises(exp_dtype, match=msg):
|
125 |
+
with tm.assert_produces_warning(FutureWarning, match=warn_msg):
|
126 |
+
temp[5] = 5
|
127 |
+
else:
|
128 |
+
exp_index = pd.Index(list("abcd") + [val], dtype=object)
|
129 |
+
self._assert_setitem_index_conversion(obj, val, exp_index, exp_dtype)
|
130 |
+
|
131 |
+
@pytest.mark.parametrize(
|
132 |
+
"val,exp_dtype", [(5, np.int64), (1.1, np.float64), ("x", object)]
|
133 |
+
)
|
134 |
+
def test_setitem_index_int64(self, val, exp_dtype):
|
135 |
+
obj = pd.Series([1, 2, 3, 4])
|
136 |
+
assert obj.index.dtype == np.int64
|
137 |
+
|
138 |
+
exp_index = pd.Index([0, 1, 2, 3, val])
|
139 |
+
self._assert_setitem_index_conversion(obj, val, exp_index, exp_dtype)
|
140 |
+
|
141 |
+
@pytest.mark.parametrize(
|
142 |
+
"val,exp_dtype", [(5, np.float64), (5.1, np.float64), ("x", object)]
|
143 |
+
)
|
144 |
+
def test_setitem_index_float64(self, val, exp_dtype, request):
|
145 |
+
obj = pd.Series([1, 2, 3, 4], index=[1.1, 2.1, 3.1, 4.1])
|
146 |
+
assert obj.index.dtype == np.float64
|
147 |
+
|
148 |
+
exp_index = pd.Index([1.1, 2.1, 3.1, 4.1, val])
|
149 |
+
self._assert_setitem_index_conversion(obj, val, exp_index, exp_dtype)
|
150 |
+
|
151 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
152 |
+
def test_setitem_series_period(self):
|
153 |
+
raise NotImplementedError
|
154 |
+
|
155 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
156 |
+
def test_setitem_index_complex128(self):
|
157 |
+
raise NotImplementedError
|
158 |
+
|
159 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
160 |
+
def test_setitem_index_bool(self):
|
161 |
+
raise NotImplementedError
|
162 |
+
|
163 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
164 |
+
def test_setitem_index_datetime64(self):
|
165 |
+
raise NotImplementedError
|
166 |
+
|
167 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
168 |
+
def test_setitem_index_datetime64tz(self):
|
169 |
+
raise NotImplementedError
|
170 |
+
|
171 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
172 |
+
def test_setitem_index_timedelta64(self):
|
173 |
+
raise NotImplementedError
|
174 |
+
|
175 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
176 |
+
def test_setitem_index_period(self):
|
177 |
+
raise NotImplementedError
|
178 |
+
|
179 |
+
|
180 |
+
class TestInsertIndexCoercion(CoercionBase):
|
181 |
+
klasses = ["index"]
|
182 |
+
method = "insert"
|
183 |
+
|
184 |
+
def _assert_insert_conversion(self, original, value, expected, expected_dtype):
|
185 |
+
"""test coercion triggered by insert"""
|
186 |
+
target = original.copy()
|
187 |
+
res = target.insert(1, value)
|
188 |
+
tm.assert_index_equal(res, expected)
|
189 |
+
assert res.dtype == expected_dtype
|
190 |
+
|
191 |
+
@pytest.mark.parametrize(
|
192 |
+
"insert, coerced_val, coerced_dtype",
|
193 |
+
[
|
194 |
+
(1, 1, object),
|
195 |
+
(1.1, 1.1, object),
|
196 |
+
(False, False, object),
|
197 |
+
("x", "x", object),
|
198 |
+
],
|
199 |
+
)
|
200 |
+
def test_insert_index_object(self, insert, coerced_val, coerced_dtype):
|
201 |
+
obj = pd.Index(list("abcd"), dtype=object)
|
202 |
+
assert obj.dtype == object
|
203 |
+
|
204 |
+
exp = pd.Index(["a", coerced_val, "b", "c", "d"], dtype=object)
|
205 |
+
self._assert_insert_conversion(obj, insert, exp, coerced_dtype)
|
206 |
+
|
207 |
+
@pytest.mark.parametrize(
|
208 |
+
"insert, coerced_val, coerced_dtype",
|
209 |
+
[
|
210 |
+
(1, 1, None),
|
211 |
+
(1.1, 1.1, np.float64),
|
212 |
+
(False, False, object), # GH#36319
|
213 |
+
("x", "x", object),
|
214 |
+
],
|
215 |
+
)
|
216 |
+
def test_insert_int_index(
|
217 |
+
self, any_int_numpy_dtype, insert, coerced_val, coerced_dtype
|
218 |
+
):
|
219 |
+
dtype = any_int_numpy_dtype
|
220 |
+
obj = pd.Index([1, 2, 3, 4], dtype=dtype)
|
221 |
+
coerced_dtype = coerced_dtype if coerced_dtype is not None else dtype
|
222 |
+
|
223 |
+
exp = pd.Index([1, coerced_val, 2, 3, 4], dtype=coerced_dtype)
|
224 |
+
self._assert_insert_conversion(obj, insert, exp, coerced_dtype)
|
225 |
+
|
226 |
+
@pytest.mark.parametrize(
|
227 |
+
"insert, coerced_val, coerced_dtype",
|
228 |
+
[
|
229 |
+
(1, 1.0, None),
|
230 |
+
# When float_numpy_dtype=float32, this is not the case
|
231 |
+
# see the correction below
|
232 |
+
(1.1, 1.1, np.float64),
|
233 |
+
(False, False, object), # GH#36319
|
234 |
+
("x", "x", object),
|
235 |
+
],
|
236 |
+
)
|
237 |
+
def test_insert_float_index(
|
238 |
+
self, float_numpy_dtype, insert, coerced_val, coerced_dtype
|
239 |
+
):
|
240 |
+
dtype = float_numpy_dtype
|
241 |
+
obj = pd.Index([1.0, 2.0, 3.0, 4.0], dtype=dtype)
|
242 |
+
coerced_dtype = coerced_dtype if coerced_dtype is not None else dtype
|
243 |
+
|
244 |
+
if np_version_gt2 and dtype == "float32" and coerced_val == 1.1:
|
245 |
+
# Hack, in the 2nd test case, since 1.1 can be losslessly cast to float32
|
246 |
+
# the expected dtype will be float32 if the original dtype was float32
|
247 |
+
coerced_dtype = np.float32
|
248 |
+
exp = pd.Index([1.0, coerced_val, 2.0, 3.0, 4.0], dtype=coerced_dtype)
|
249 |
+
self._assert_insert_conversion(obj, insert, exp, coerced_dtype)
|
250 |
+
|
251 |
+
@pytest.mark.parametrize(
|
252 |
+
"fill_val,exp_dtype",
|
253 |
+
[
|
254 |
+
(pd.Timestamp("2012-01-01"), "datetime64[ns]"),
|
255 |
+
(pd.Timestamp("2012-01-01", tz="US/Eastern"), "datetime64[ns, US/Eastern]"),
|
256 |
+
],
|
257 |
+
ids=["datetime64", "datetime64tz"],
|
258 |
+
)
|
259 |
+
@pytest.mark.parametrize(
|
260 |
+
"insert_value",
|
261 |
+
[pd.Timestamp("2012-01-01"), pd.Timestamp("2012-01-01", tz="Asia/Tokyo"), 1],
|
262 |
+
)
|
263 |
+
def test_insert_index_datetimes(self, fill_val, exp_dtype, insert_value):
|
264 |
+
obj = pd.DatetimeIndex(
|
265 |
+
["2011-01-01", "2011-01-02", "2011-01-03", "2011-01-04"], tz=fill_val.tz
|
266 |
+
).as_unit("ns")
|
267 |
+
assert obj.dtype == exp_dtype
|
268 |
+
|
269 |
+
exp = pd.DatetimeIndex(
|
270 |
+
["2011-01-01", fill_val.date(), "2011-01-02", "2011-01-03", "2011-01-04"],
|
271 |
+
tz=fill_val.tz,
|
272 |
+
).as_unit("ns")
|
273 |
+
self._assert_insert_conversion(obj, fill_val, exp, exp_dtype)
|
274 |
+
|
275 |
+
if fill_val.tz:
|
276 |
+
# mismatched tzawareness
|
277 |
+
ts = pd.Timestamp("2012-01-01")
|
278 |
+
result = obj.insert(1, ts)
|
279 |
+
expected = obj.astype(object).insert(1, ts)
|
280 |
+
assert expected.dtype == object
|
281 |
+
tm.assert_index_equal(result, expected)
|
282 |
+
|
283 |
+
ts = pd.Timestamp("2012-01-01", tz="Asia/Tokyo")
|
284 |
+
result = obj.insert(1, ts)
|
285 |
+
# once deprecation is enforced:
|
286 |
+
expected = obj.insert(1, ts.tz_convert(obj.dtype.tz))
|
287 |
+
assert expected.dtype == obj.dtype
|
288 |
+
tm.assert_index_equal(result, expected)
|
289 |
+
|
290 |
+
else:
|
291 |
+
# mismatched tzawareness
|
292 |
+
ts = pd.Timestamp("2012-01-01", tz="Asia/Tokyo")
|
293 |
+
result = obj.insert(1, ts)
|
294 |
+
expected = obj.astype(object).insert(1, ts)
|
295 |
+
assert expected.dtype == object
|
296 |
+
tm.assert_index_equal(result, expected)
|
297 |
+
|
298 |
+
item = 1
|
299 |
+
result = obj.insert(1, item)
|
300 |
+
expected = obj.astype(object).insert(1, item)
|
301 |
+
assert expected[1] == item
|
302 |
+
assert expected.dtype == object
|
303 |
+
tm.assert_index_equal(result, expected)
|
304 |
+
|
305 |
+
def test_insert_index_timedelta64(self):
|
306 |
+
obj = pd.TimedeltaIndex(["1 day", "2 day", "3 day", "4 day"])
|
307 |
+
assert obj.dtype == "timedelta64[ns]"
|
308 |
+
|
309 |
+
# timedelta64 + timedelta64 => timedelta64
|
310 |
+
exp = pd.TimedeltaIndex(["1 day", "10 day", "2 day", "3 day", "4 day"])
|
311 |
+
self._assert_insert_conversion(
|
312 |
+
obj, pd.Timedelta("10 day"), exp, "timedelta64[ns]"
|
313 |
+
)
|
314 |
+
|
315 |
+
for item in [pd.Timestamp("2012-01-01"), 1]:
|
316 |
+
result = obj.insert(1, item)
|
317 |
+
expected = obj.astype(object).insert(1, item)
|
318 |
+
assert expected.dtype == object
|
319 |
+
tm.assert_index_equal(result, expected)
|
320 |
+
|
321 |
+
@pytest.mark.parametrize(
|
322 |
+
"insert, coerced_val, coerced_dtype",
|
323 |
+
[
|
324 |
+
(pd.Period("2012-01", freq="M"), "2012-01", "period[M]"),
|
325 |
+
(pd.Timestamp("2012-01-01"), pd.Timestamp("2012-01-01"), object),
|
326 |
+
(1, 1, object),
|
327 |
+
("x", "x", object),
|
328 |
+
],
|
329 |
+
)
|
330 |
+
def test_insert_index_period(self, insert, coerced_val, coerced_dtype):
|
331 |
+
obj = pd.PeriodIndex(["2011-01", "2011-02", "2011-03", "2011-04"], freq="M")
|
332 |
+
assert obj.dtype == "period[M]"
|
333 |
+
|
334 |
+
data = [
|
335 |
+
pd.Period("2011-01", freq="M"),
|
336 |
+
coerced_val,
|
337 |
+
pd.Period("2011-02", freq="M"),
|
338 |
+
pd.Period("2011-03", freq="M"),
|
339 |
+
pd.Period("2011-04", freq="M"),
|
340 |
+
]
|
341 |
+
if isinstance(insert, pd.Period):
|
342 |
+
exp = pd.PeriodIndex(data, freq="M")
|
343 |
+
self._assert_insert_conversion(obj, insert, exp, coerced_dtype)
|
344 |
+
|
345 |
+
# string that can be parsed to appropriate PeriodDtype
|
346 |
+
self._assert_insert_conversion(obj, str(insert), exp, coerced_dtype)
|
347 |
+
|
348 |
+
else:
|
349 |
+
result = obj.insert(0, insert)
|
350 |
+
expected = obj.astype(object).insert(0, insert)
|
351 |
+
tm.assert_index_equal(result, expected)
|
352 |
+
|
353 |
+
# TODO: ATM inserting '2012-01-01 00:00:00' when we have obj.freq=="M"
|
354 |
+
# casts that string to Period[M], not clear that is desirable
|
355 |
+
if not isinstance(insert, pd.Timestamp):
|
356 |
+
# non-castable string
|
357 |
+
result = obj.insert(0, str(insert))
|
358 |
+
expected = obj.astype(object).insert(0, str(insert))
|
359 |
+
tm.assert_index_equal(result, expected)
|
360 |
+
|
361 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
362 |
+
def test_insert_index_complex128(self):
|
363 |
+
raise NotImplementedError
|
364 |
+
|
365 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
366 |
+
def test_insert_index_bool(self):
|
367 |
+
raise NotImplementedError
|
368 |
+
|
369 |
+
|
370 |
+
class TestWhereCoercion(CoercionBase):
|
371 |
+
method = "where"
|
372 |
+
_cond = np.array([True, False, True, False])
|
373 |
+
|
374 |
+
def _assert_where_conversion(
|
375 |
+
self, original, cond, values, expected, expected_dtype
|
376 |
+
):
|
377 |
+
"""test coercion triggered by where"""
|
378 |
+
target = original.copy()
|
379 |
+
res = target.where(cond, values)
|
380 |
+
tm.assert_equal(res, expected)
|
381 |
+
assert res.dtype == expected_dtype
|
382 |
+
|
383 |
+
def _construct_exp(self, obj, klass, fill_val, exp_dtype):
|
384 |
+
if fill_val is True:
|
385 |
+
values = klass([True, False, True, True])
|
386 |
+
elif isinstance(fill_val, (datetime, np.datetime64)):
|
387 |
+
values = pd.date_range(fill_val, periods=4)
|
388 |
+
else:
|
389 |
+
values = klass(x * fill_val for x in [5, 6, 7, 8])
|
390 |
+
|
391 |
+
exp = klass([obj[0], values[1], obj[2], values[3]], dtype=exp_dtype)
|
392 |
+
return values, exp
|
393 |
+
|
394 |
+
def _run_test(self, obj, fill_val, klass, exp_dtype):
|
395 |
+
cond = klass(self._cond)
|
396 |
+
|
397 |
+
exp = klass([obj[0], fill_val, obj[2], fill_val], dtype=exp_dtype)
|
398 |
+
self._assert_where_conversion(obj, cond, fill_val, exp, exp_dtype)
|
399 |
+
|
400 |
+
values, exp = self._construct_exp(obj, klass, fill_val, exp_dtype)
|
401 |
+
self._assert_where_conversion(obj, cond, values, exp, exp_dtype)
|
402 |
+
|
403 |
+
@pytest.mark.parametrize(
|
404 |
+
"fill_val,exp_dtype",
|
405 |
+
[(1, object), (1.1, object), (1 + 1j, object), (True, object)],
|
406 |
+
)
|
407 |
+
def test_where_object(self, index_or_series, fill_val, exp_dtype):
|
408 |
+
klass = index_or_series
|
409 |
+
obj = klass(list("abcd"), dtype=object)
|
410 |
+
assert obj.dtype == object
|
411 |
+
self._run_test(obj, fill_val, klass, exp_dtype)
|
412 |
+
|
413 |
+
@pytest.mark.parametrize(
|
414 |
+
"fill_val,exp_dtype",
|
415 |
+
[(1, np.int64), (1.1, np.float64), (1 + 1j, np.complex128), (True, object)],
|
416 |
+
)
|
417 |
+
def test_where_int64(self, index_or_series, fill_val, exp_dtype, request):
|
418 |
+
klass = index_or_series
|
419 |
+
|
420 |
+
obj = klass([1, 2, 3, 4])
|
421 |
+
assert obj.dtype == np.int64
|
422 |
+
self._run_test(obj, fill_val, klass, exp_dtype)
|
423 |
+
|
424 |
+
@pytest.mark.parametrize(
|
425 |
+
"fill_val, exp_dtype",
|
426 |
+
[(1, np.float64), (1.1, np.float64), (1 + 1j, np.complex128), (True, object)],
|
427 |
+
)
|
428 |
+
def test_where_float64(self, index_or_series, fill_val, exp_dtype, request):
|
429 |
+
klass = index_or_series
|
430 |
+
|
431 |
+
obj = klass([1.1, 2.2, 3.3, 4.4])
|
432 |
+
assert obj.dtype == np.float64
|
433 |
+
self._run_test(obj, fill_val, klass, exp_dtype)
|
434 |
+
|
435 |
+
@pytest.mark.parametrize(
|
436 |
+
"fill_val,exp_dtype",
|
437 |
+
[
|
438 |
+
(1, np.complex128),
|
439 |
+
(1.1, np.complex128),
|
440 |
+
(1 + 1j, np.complex128),
|
441 |
+
(True, object),
|
442 |
+
],
|
443 |
+
)
|
444 |
+
def test_where_complex128(self, index_or_series, fill_val, exp_dtype):
|
445 |
+
klass = index_or_series
|
446 |
+
obj = klass([1 + 1j, 2 + 2j, 3 + 3j, 4 + 4j], dtype=np.complex128)
|
447 |
+
assert obj.dtype == np.complex128
|
448 |
+
self._run_test(obj, fill_val, klass, exp_dtype)
|
449 |
+
|
450 |
+
@pytest.mark.parametrize(
|
451 |
+
"fill_val,exp_dtype",
|
452 |
+
[(1, object), (1.1, object), (1 + 1j, object), (True, np.bool_)],
|
453 |
+
)
|
454 |
+
def test_where_series_bool(self, index_or_series, fill_val, exp_dtype):
|
455 |
+
klass = index_or_series
|
456 |
+
|
457 |
+
obj = klass([True, False, True, False])
|
458 |
+
assert obj.dtype == np.bool_
|
459 |
+
self._run_test(obj, fill_val, klass, exp_dtype)
|
460 |
+
|
461 |
+
@pytest.mark.parametrize(
|
462 |
+
"fill_val,exp_dtype",
|
463 |
+
[
|
464 |
+
(pd.Timestamp("2012-01-01"), "datetime64[ns]"),
|
465 |
+
(pd.Timestamp("2012-01-01", tz="US/Eastern"), object),
|
466 |
+
],
|
467 |
+
ids=["datetime64", "datetime64tz"],
|
468 |
+
)
|
469 |
+
def test_where_datetime64(self, index_or_series, fill_val, exp_dtype):
|
470 |
+
klass = index_or_series
|
471 |
+
|
472 |
+
obj = klass(pd.date_range("2011-01-01", periods=4, freq="D")._with_freq(None))
|
473 |
+
assert obj.dtype == "datetime64[ns]"
|
474 |
+
|
475 |
+
fv = fill_val
|
476 |
+
# do the check with each of the available datetime scalars
|
477 |
+
if exp_dtype == "datetime64[ns]":
|
478 |
+
for scalar in [fv, fv.to_pydatetime(), fv.to_datetime64()]:
|
479 |
+
self._run_test(obj, scalar, klass, exp_dtype)
|
480 |
+
else:
|
481 |
+
for scalar in [fv, fv.to_pydatetime()]:
|
482 |
+
self._run_test(obj, fill_val, klass, exp_dtype)
|
483 |
+
|
484 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
485 |
+
def test_where_index_complex128(self):
|
486 |
+
raise NotImplementedError
|
487 |
+
|
488 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
489 |
+
def test_where_index_bool(self):
|
490 |
+
raise NotImplementedError
|
491 |
+
|
492 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
493 |
+
def test_where_series_timedelta64(self):
|
494 |
+
raise NotImplementedError
|
495 |
+
|
496 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
497 |
+
def test_where_series_period(self):
|
498 |
+
raise NotImplementedError
|
499 |
+
|
500 |
+
@pytest.mark.parametrize(
|
501 |
+
"value", [pd.Timedelta(days=9), timedelta(days=9), np.timedelta64(9, "D")]
|
502 |
+
)
|
503 |
+
def test_where_index_timedelta64(self, value):
|
504 |
+
tdi = pd.timedelta_range("1 Day", periods=4)
|
505 |
+
cond = np.array([True, False, False, True])
|
506 |
+
|
507 |
+
expected = pd.TimedeltaIndex(["1 Day", value, value, "4 Days"])
|
508 |
+
result = tdi.where(cond, value)
|
509 |
+
tm.assert_index_equal(result, expected)
|
510 |
+
|
511 |
+
# wrong-dtyped NaT
|
512 |
+
dtnat = np.datetime64("NaT", "ns")
|
513 |
+
expected = pd.Index([tdi[0], dtnat, dtnat, tdi[3]], dtype=object)
|
514 |
+
assert expected[1] is dtnat
|
515 |
+
|
516 |
+
result = tdi.where(cond, dtnat)
|
517 |
+
tm.assert_index_equal(result, expected)
|
518 |
+
|
519 |
+
def test_where_index_period(self):
|
520 |
+
dti = pd.date_range("2016-01-01", periods=3, freq="QS")
|
521 |
+
pi = dti.to_period("Q")
|
522 |
+
|
523 |
+
cond = np.array([False, True, False])
|
524 |
+
|
525 |
+
# Passing a valid scalar
|
526 |
+
value = pi[-1] + pi.freq * 10
|
527 |
+
expected = pd.PeriodIndex([value, pi[1], value])
|
528 |
+
result = pi.where(cond, value)
|
529 |
+
tm.assert_index_equal(result, expected)
|
530 |
+
|
531 |
+
# Case passing ndarray[object] of Periods
|
532 |
+
other = np.asarray(pi + pi.freq * 10, dtype=object)
|
533 |
+
result = pi.where(cond, other)
|
534 |
+
expected = pd.PeriodIndex([other[0], pi[1], other[2]])
|
535 |
+
tm.assert_index_equal(result, expected)
|
536 |
+
|
537 |
+
# Passing a mismatched scalar -> casts to object
|
538 |
+
td = pd.Timedelta(days=4)
|
539 |
+
expected = pd.Index([td, pi[1], td], dtype=object)
|
540 |
+
result = pi.where(cond, td)
|
541 |
+
tm.assert_index_equal(result, expected)
|
542 |
+
|
543 |
+
per = pd.Period("2020-04-21", "D")
|
544 |
+
expected = pd.Index([per, pi[1], per], dtype=object)
|
545 |
+
result = pi.where(cond, per)
|
546 |
+
tm.assert_index_equal(result, expected)
|
547 |
+
|
548 |
+
|
549 |
+
class TestFillnaSeriesCoercion(CoercionBase):
|
550 |
+
# not indexing, but place here for consistency
|
551 |
+
|
552 |
+
method = "fillna"
|
553 |
+
|
554 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
555 |
+
def test_has_comprehensive_tests(self):
|
556 |
+
raise NotImplementedError
|
557 |
+
|
558 |
+
def _assert_fillna_conversion(self, original, value, expected, expected_dtype):
|
559 |
+
"""test coercion triggered by fillna"""
|
560 |
+
target = original.copy()
|
561 |
+
res = target.fillna(value)
|
562 |
+
tm.assert_equal(res, expected)
|
563 |
+
assert res.dtype == expected_dtype
|
564 |
+
|
565 |
+
@pytest.mark.parametrize(
|
566 |
+
"fill_val, fill_dtype",
|
567 |
+
[(1, object), (1.1, object), (1 + 1j, object), (True, object)],
|
568 |
+
)
|
569 |
+
def test_fillna_object(self, index_or_series, fill_val, fill_dtype):
|
570 |
+
klass = index_or_series
|
571 |
+
obj = klass(["a", np.nan, "c", "d"], dtype=object)
|
572 |
+
assert obj.dtype == object
|
573 |
+
|
574 |
+
exp = klass(["a", fill_val, "c", "d"], dtype=object)
|
575 |
+
self._assert_fillna_conversion(obj, fill_val, exp, fill_dtype)
|
576 |
+
|
577 |
+
@pytest.mark.parametrize(
|
578 |
+
"fill_val,fill_dtype",
|
579 |
+
[(1, np.float64), (1.1, np.float64), (1 + 1j, np.complex128), (True, object)],
|
580 |
+
)
|
581 |
+
def test_fillna_float64(self, index_or_series, fill_val, fill_dtype):
|
582 |
+
klass = index_or_series
|
583 |
+
obj = klass([1.1, np.nan, 3.3, 4.4])
|
584 |
+
assert obj.dtype == np.float64
|
585 |
+
|
586 |
+
exp = klass([1.1, fill_val, 3.3, 4.4])
|
587 |
+
self._assert_fillna_conversion(obj, fill_val, exp, fill_dtype)
|
588 |
+
|
589 |
+
@pytest.mark.parametrize(
|
590 |
+
"fill_val,fill_dtype",
|
591 |
+
[
|
592 |
+
(1, np.complex128),
|
593 |
+
(1.1, np.complex128),
|
594 |
+
(1 + 1j, np.complex128),
|
595 |
+
(True, object),
|
596 |
+
],
|
597 |
+
)
|
598 |
+
def test_fillna_complex128(self, index_or_series, fill_val, fill_dtype):
|
599 |
+
klass = index_or_series
|
600 |
+
obj = klass([1 + 1j, np.nan, 3 + 3j, 4 + 4j], dtype=np.complex128)
|
601 |
+
assert obj.dtype == np.complex128
|
602 |
+
|
603 |
+
exp = klass([1 + 1j, fill_val, 3 + 3j, 4 + 4j])
|
604 |
+
self._assert_fillna_conversion(obj, fill_val, exp, fill_dtype)
|
605 |
+
|
606 |
+
@pytest.mark.parametrize(
|
607 |
+
"fill_val,fill_dtype",
|
608 |
+
[
|
609 |
+
(pd.Timestamp("2012-01-01"), "datetime64[ns]"),
|
610 |
+
(pd.Timestamp("2012-01-01", tz="US/Eastern"), object),
|
611 |
+
(1, object),
|
612 |
+
("x", object),
|
613 |
+
],
|
614 |
+
ids=["datetime64", "datetime64tz", "object", "object"],
|
615 |
+
)
|
616 |
+
def test_fillna_datetime(self, index_or_series, fill_val, fill_dtype):
|
617 |
+
klass = index_or_series
|
618 |
+
obj = klass(
|
619 |
+
[
|
620 |
+
pd.Timestamp("2011-01-01"),
|
621 |
+
pd.NaT,
|
622 |
+
pd.Timestamp("2011-01-03"),
|
623 |
+
pd.Timestamp("2011-01-04"),
|
624 |
+
]
|
625 |
+
)
|
626 |
+
assert obj.dtype == "datetime64[ns]"
|
627 |
+
|
628 |
+
exp = klass(
|
629 |
+
[
|
630 |
+
pd.Timestamp("2011-01-01"),
|
631 |
+
fill_val,
|
632 |
+
pd.Timestamp("2011-01-03"),
|
633 |
+
pd.Timestamp("2011-01-04"),
|
634 |
+
]
|
635 |
+
)
|
636 |
+
self._assert_fillna_conversion(obj, fill_val, exp, fill_dtype)
|
637 |
+
|
638 |
+
@pytest.mark.parametrize(
|
639 |
+
"fill_val,fill_dtype",
|
640 |
+
[
|
641 |
+
(pd.Timestamp("2012-01-01", tz="US/Eastern"), "datetime64[ns, US/Eastern]"),
|
642 |
+
(pd.Timestamp("2012-01-01"), object),
|
643 |
+
# pre-2.0 with a mismatched tz we would get object result
|
644 |
+
(pd.Timestamp("2012-01-01", tz="Asia/Tokyo"), "datetime64[ns, US/Eastern]"),
|
645 |
+
(1, object),
|
646 |
+
("x", object),
|
647 |
+
],
|
648 |
+
)
|
649 |
+
def test_fillna_datetime64tz(self, index_or_series, fill_val, fill_dtype):
|
650 |
+
klass = index_or_series
|
651 |
+
tz = "US/Eastern"
|
652 |
+
|
653 |
+
obj = klass(
|
654 |
+
[
|
655 |
+
pd.Timestamp("2011-01-01", tz=tz),
|
656 |
+
pd.NaT,
|
657 |
+
pd.Timestamp("2011-01-03", tz=tz),
|
658 |
+
pd.Timestamp("2011-01-04", tz=tz),
|
659 |
+
]
|
660 |
+
)
|
661 |
+
assert obj.dtype == "datetime64[ns, US/Eastern]"
|
662 |
+
|
663 |
+
if getattr(fill_val, "tz", None) is None:
|
664 |
+
fv = fill_val
|
665 |
+
else:
|
666 |
+
fv = fill_val.tz_convert(tz)
|
667 |
+
exp = klass(
|
668 |
+
[
|
669 |
+
pd.Timestamp("2011-01-01", tz=tz),
|
670 |
+
fv,
|
671 |
+
pd.Timestamp("2011-01-03", tz=tz),
|
672 |
+
pd.Timestamp("2011-01-04", tz=tz),
|
673 |
+
]
|
674 |
+
)
|
675 |
+
self._assert_fillna_conversion(obj, fill_val, exp, fill_dtype)
|
676 |
+
|
677 |
+
@pytest.mark.parametrize(
|
678 |
+
"fill_val",
|
679 |
+
[
|
680 |
+
1,
|
681 |
+
1.1,
|
682 |
+
1 + 1j,
|
683 |
+
True,
|
684 |
+
pd.Interval(1, 2, closed="left"),
|
685 |
+
pd.Timestamp("2012-01-01", tz="US/Eastern"),
|
686 |
+
pd.Timestamp("2012-01-01"),
|
687 |
+
pd.Timedelta(days=1),
|
688 |
+
pd.Period("2016-01-01", "D"),
|
689 |
+
],
|
690 |
+
)
|
691 |
+
def test_fillna_interval(self, index_or_series, fill_val):
|
692 |
+
ii = pd.interval_range(1.0, 5.0, closed="right").insert(1, np.nan)
|
693 |
+
assert isinstance(ii.dtype, pd.IntervalDtype)
|
694 |
+
obj = index_or_series(ii)
|
695 |
+
|
696 |
+
exp = index_or_series([ii[0], fill_val, ii[2], ii[3], ii[4]], dtype=object)
|
697 |
+
|
698 |
+
fill_dtype = object
|
699 |
+
self._assert_fillna_conversion(obj, fill_val, exp, fill_dtype)
|
700 |
+
|
701 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
702 |
+
def test_fillna_series_int64(self):
|
703 |
+
raise NotImplementedError
|
704 |
+
|
705 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
706 |
+
def test_fillna_index_int64(self):
|
707 |
+
raise NotImplementedError
|
708 |
+
|
709 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
710 |
+
def test_fillna_series_bool(self):
|
711 |
+
raise NotImplementedError
|
712 |
+
|
713 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
714 |
+
def test_fillna_index_bool(self):
|
715 |
+
raise NotImplementedError
|
716 |
+
|
717 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
718 |
+
def test_fillna_series_timedelta64(self):
|
719 |
+
raise NotImplementedError
|
720 |
+
|
721 |
+
@pytest.mark.parametrize(
|
722 |
+
"fill_val",
|
723 |
+
[
|
724 |
+
1,
|
725 |
+
1.1,
|
726 |
+
1 + 1j,
|
727 |
+
True,
|
728 |
+
pd.Interval(1, 2, closed="left"),
|
729 |
+
pd.Timestamp("2012-01-01", tz="US/Eastern"),
|
730 |
+
pd.Timestamp("2012-01-01"),
|
731 |
+
pd.Timedelta(days=1),
|
732 |
+
pd.Period("2016-01-01", "W"),
|
733 |
+
],
|
734 |
+
)
|
735 |
+
def test_fillna_series_period(self, index_or_series, fill_val):
|
736 |
+
pi = pd.period_range("2016-01-01", periods=4, freq="D").insert(1, pd.NaT)
|
737 |
+
assert isinstance(pi.dtype, pd.PeriodDtype)
|
738 |
+
obj = index_or_series(pi)
|
739 |
+
|
740 |
+
exp = index_or_series([pi[0], fill_val, pi[2], pi[3], pi[4]], dtype=object)
|
741 |
+
|
742 |
+
fill_dtype = object
|
743 |
+
self._assert_fillna_conversion(obj, fill_val, exp, fill_dtype)
|
744 |
+
|
745 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
746 |
+
def test_fillna_index_timedelta64(self):
|
747 |
+
raise NotImplementedError
|
748 |
+
|
749 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
750 |
+
def test_fillna_index_period(self):
|
751 |
+
raise NotImplementedError
|
752 |
+
|
753 |
+
|
754 |
+
class TestReplaceSeriesCoercion(CoercionBase):
|
755 |
+
klasses = ["series"]
|
756 |
+
method = "replace"
|
757 |
+
|
758 |
+
rep: dict[str, list] = {}
|
759 |
+
rep["object"] = ["a", "b"]
|
760 |
+
rep["int64"] = [4, 5]
|
761 |
+
rep["float64"] = [1.1, 2.2]
|
762 |
+
rep["complex128"] = [1 + 1j, 2 + 2j]
|
763 |
+
rep["bool"] = [True, False]
|
764 |
+
rep["datetime64[ns]"] = [pd.Timestamp("2011-01-01"), pd.Timestamp("2011-01-03")]
|
765 |
+
|
766 |
+
for tz in ["UTC", "US/Eastern"]:
|
767 |
+
# to test tz => different tz replacement
|
768 |
+
key = f"datetime64[ns, {tz}]"
|
769 |
+
rep[key] = [
|
770 |
+
pd.Timestamp("2011-01-01", tz=tz),
|
771 |
+
pd.Timestamp("2011-01-03", tz=tz),
|
772 |
+
]
|
773 |
+
|
774 |
+
rep["timedelta64[ns]"] = [pd.Timedelta("1 day"), pd.Timedelta("2 day")]
|
775 |
+
|
776 |
+
@pytest.fixture(params=["dict", "series"])
|
777 |
+
def how(self, request):
|
778 |
+
return request.param
|
779 |
+
|
780 |
+
@pytest.fixture(
|
781 |
+
params=[
|
782 |
+
"object",
|
783 |
+
"int64",
|
784 |
+
"float64",
|
785 |
+
"complex128",
|
786 |
+
"bool",
|
787 |
+
"datetime64[ns]",
|
788 |
+
"datetime64[ns, UTC]",
|
789 |
+
"datetime64[ns, US/Eastern]",
|
790 |
+
"timedelta64[ns]",
|
791 |
+
]
|
792 |
+
)
|
793 |
+
def from_key(self, request):
|
794 |
+
return request.param
|
795 |
+
|
796 |
+
@pytest.fixture(
|
797 |
+
params=[
|
798 |
+
"object",
|
799 |
+
"int64",
|
800 |
+
"float64",
|
801 |
+
"complex128",
|
802 |
+
"bool",
|
803 |
+
"datetime64[ns]",
|
804 |
+
"datetime64[ns, UTC]",
|
805 |
+
"datetime64[ns, US/Eastern]",
|
806 |
+
"timedelta64[ns]",
|
807 |
+
],
|
808 |
+
ids=[
|
809 |
+
"object",
|
810 |
+
"int64",
|
811 |
+
"float64",
|
812 |
+
"complex128",
|
813 |
+
"bool",
|
814 |
+
"datetime64",
|
815 |
+
"datetime64tz",
|
816 |
+
"datetime64tz",
|
817 |
+
"timedelta64",
|
818 |
+
],
|
819 |
+
)
|
820 |
+
def to_key(self, request):
|
821 |
+
return request.param
|
822 |
+
|
823 |
+
@pytest.fixture
|
824 |
+
def replacer(self, how, from_key, to_key):
|
825 |
+
"""
|
826 |
+
Object we will pass to `Series.replace`
|
827 |
+
"""
|
828 |
+
if how == "dict":
|
829 |
+
replacer = dict(zip(self.rep[from_key], self.rep[to_key]))
|
830 |
+
elif how == "series":
|
831 |
+
replacer = pd.Series(self.rep[to_key], index=self.rep[from_key])
|
832 |
+
else:
|
833 |
+
raise ValueError
|
834 |
+
return replacer
|
835 |
+
|
836 |
+
# Expected needs adjustment for the infer string option, seems to work as expecetd
|
837 |
+
@pytest.mark.skipif(using_pyarrow_string_dtype(), reason="TODO: test is to complex")
|
838 |
+
def test_replace_series(self, how, to_key, from_key, replacer):
|
839 |
+
index = pd.Index([3, 4], name="xxx")
|
840 |
+
obj = pd.Series(self.rep[from_key], index=index, name="yyy")
|
841 |
+
assert obj.dtype == from_key
|
842 |
+
|
843 |
+
if from_key.startswith("datetime") and to_key.startswith("datetime"):
|
844 |
+
# tested below
|
845 |
+
return
|
846 |
+
elif from_key in ["datetime64[ns, US/Eastern]", "datetime64[ns, UTC]"]:
|
847 |
+
# tested below
|
848 |
+
return
|
849 |
+
|
850 |
+
if (from_key == "float64" and to_key in ("int64")) or (
|
851 |
+
from_key == "complex128" and to_key in ("int64", "float64")
|
852 |
+
):
|
853 |
+
if not IS64 or is_platform_windows():
|
854 |
+
pytest.skip(f"32-bit platform buggy: {from_key} -> {to_key}")
|
855 |
+
|
856 |
+
# Expected: do not downcast by replacement
|
857 |
+
exp = pd.Series(self.rep[to_key], index=index, name="yyy", dtype=from_key)
|
858 |
+
|
859 |
+
else:
|
860 |
+
exp = pd.Series(self.rep[to_key], index=index, name="yyy")
|
861 |
+
assert exp.dtype == to_key
|
862 |
+
|
863 |
+
msg = "Downcasting behavior in `replace`"
|
864 |
+
warn = FutureWarning
|
865 |
+
if (
|
866 |
+
exp.dtype == obj.dtype
|
867 |
+
or exp.dtype == object
|
868 |
+
or (exp.dtype.kind in "iufc" and obj.dtype.kind in "iufc")
|
869 |
+
):
|
870 |
+
warn = None
|
871 |
+
with tm.assert_produces_warning(warn, match=msg):
|
872 |
+
result = obj.replace(replacer)
|
873 |
+
|
874 |
+
tm.assert_series_equal(result, exp)
|
875 |
+
|
876 |
+
@pytest.mark.parametrize(
|
877 |
+
"to_key",
|
878 |
+
["timedelta64[ns]", "bool", "object", "complex128", "float64", "int64"],
|
879 |
+
indirect=True,
|
880 |
+
)
|
881 |
+
@pytest.mark.parametrize(
|
882 |
+
"from_key", ["datetime64[ns, UTC]", "datetime64[ns, US/Eastern]"], indirect=True
|
883 |
+
)
|
884 |
+
def test_replace_series_datetime_tz(
|
885 |
+
self, how, to_key, from_key, replacer, using_infer_string
|
886 |
+
):
|
887 |
+
index = pd.Index([3, 4], name="xyz")
|
888 |
+
obj = pd.Series(self.rep[from_key], index=index, name="yyy")
|
889 |
+
assert obj.dtype == from_key
|
890 |
+
|
891 |
+
exp = pd.Series(self.rep[to_key], index=index, name="yyy")
|
892 |
+
if using_infer_string and to_key == "object":
|
893 |
+
assert exp.dtype == "string"
|
894 |
+
else:
|
895 |
+
assert exp.dtype == to_key
|
896 |
+
|
897 |
+
msg = "Downcasting behavior in `replace`"
|
898 |
+
warn = FutureWarning if exp.dtype != object else None
|
899 |
+
with tm.assert_produces_warning(warn, match=msg):
|
900 |
+
result = obj.replace(replacer)
|
901 |
+
|
902 |
+
tm.assert_series_equal(result, exp)
|
903 |
+
|
904 |
+
@pytest.mark.parametrize(
|
905 |
+
"to_key",
|
906 |
+
["datetime64[ns]", "datetime64[ns, UTC]", "datetime64[ns, US/Eastern]"],
|
907 |
+
indirect=True,
|
908 |
+
)
|
909 |
+
@pytest.mark.parametrize(
|
910 |
+
"from_key",
|
911 |
+
["datetime64[ns]", "datetime64[ns, UTC]", "datetime64[ns, US/Eastern]"],
|
912 |
+
indirect=True,
|
913 |
+
)
|
914 |
+
def test_replace_series_datetime_datetime(self, how, to_key, from_key, replacer):
|
915 |
+
index = pd.Index([3, 4], name="xyz")
|
916 |
+
obj = pd.Series(self.rep[from_key], index=index, name="yyy")
|
917 |
+
assert obj.dtype == from_key
|
918 |
+
|
919 |
+
exp = pd.Series(self.rep[to_key], index=index, name="yyy")
|
920 |
+
warn = FutureWarning
|
921 |
+
if isinstance(obj.dtype, pd.DatetimeTZDtype) and isinstance(
|
922 |
+
exp.dtype, pd.DatetimeTZDtype
|
923 |
+
):
|
924 |
+
# with mismatched tzs, we retain the original dtype as of 2.0
|
925 |
+
exp = exp.astype(obj.dtype)
|
926 |
+
warn = None
|
927 |
+
else:
|
928 |
+
assert exp.dtype == to_key
|
929 |
+
if to_key == from_key:
|
930 |
+
warn = None
|
931 |
+
|
932 |
+
msg = "Downcasting behavior in `replace`"
|
933 |
+
with tm.assert_produces_warning(warn, match=msg):
|
934 |
+
result = obj.replace(replacer)
|
935 |
+
|
936 |
+
tm.assert_series_equal(result, exp)
|
937 |
+
|
938 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
939 |
+
def test_replace_series_period(self):
|
940 |
+
raise NotImplementedError
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/test_datetime.py
ADDED
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
|
3 |
+
import pytest
|
4 |
+
|
5 |
+
import pandas as pd
|
6 |
+
from pandas import (
|
7 |
+
DataFrame,
|
8 |
+
Index,
|
9 |
+
Series,
|
10 |
+
Timestamp,
|
11 |
+
date_range,
|
12 |
+
)
|
13 |
+
import pandas._testing as tm
|
14 |
+
|
15 |
+
|
16 |
+
class TestDatetimeIndex:
|
17 |
+
def test_get_loc_naive_dti_aware_str_deprecated(self):
|
18 |
+
# GH#46903
|
19 |
+
ts = Timestamp("20130101")._value
|
20 |
+
dti = pd.DatetimeIndex([ts + 50 + i for i in range(100)])
|
21 |
+
ser = Series(range(100), index=dti)
|
22 |
+
|
23 |
+
key = "2013-01-01 00:00:00.000000050+0000"
|
24 |
+
msg = re.escape(repr(key))
|
25 |
+
with pytest.raises(KeyError, match=msg):
|
26 |
+
ser[key]
|
27 |
+
|
28 |
+
with pytest.raises(KeyError, match=msg):
|
29 |
+
dti.get_loc(key)
|
30 |
+
|
31 |
+
def test_indexing_with_datetime_tz(self):
|
32 |
+
# GH#8260
|
33 |
+
# support datetime64 with tz
|
34 |
+
|
35 |
+
idx = Index(date_range("20130101", periods=3, tz="US/Eastern"), name="foo")
|
36 |
+
dr = date_range("20130110", periods=3)
|
37 |
+
df = DataFrame({"A": idx, "B": dr})
|
38 |
+
df["C"] = idx
|
39 |
+
df.iloc[1, 1] = pd.NaT
|
40 |
+
df.iloc[1, 2] = pd.NaT
|
41 |
+
|
42 |
+
expected = Series(
|
43 |
+
[Timestamp("2013-01-02 00:00:00-0500", tz="US/Eastern"), pd.NaT, pd.NaT],
|
44 |
+
index=list("ABC"),
|
45 |
+
dtype="object",
|
46 |
+
name=1,
|
47 |
+
)
|
48 |
+
|
49 |
+
# indexing
|
50 |
+
result = df.iloc[1]
|
51 |
+
tm.assert_series_equal(result, expected)
|
52 |
+
result = df.loc[1]
|
53 |
+
tm.assert_series_equal(result, expected)
|
54 |
+
|
55 |
+
def test_indexing_fast_xs(self):
|
56 |
+
# indexing - fast_xs
|
57 |
+
df = DataFrame({"a": date_range("2014-01-01", periods=10, tz="UTC")})
|
58 |
+
result = df.iloc[5]
|
59 |
+
expected = Series(
|
60 |
+
[Timestamp("2014-01-06 00:00:00+0000", tz="UTC")],
|
61 |
+
index=["a"],
|
62 |
+
name=5,
|
63 |
+
dtype="M8[ns, UTC]",
|
64 |
+
)
|
65 |
+
tm.assert_series_equal(result, expected)
|
66 |
+
|
67 |
+
result = df.loc[5]
|
68 |
+
tm.assert_series_equal(result, expected)
|
69 |
+
|
70 |
+
# indexing - boolean
|
71 |
+
result = df[df.a > df.a[3]]
|
72 |
+
expected = df.iloc[4:]
|
73 |
+
tm.assert_frame_equal(result, expected)
|
74 |
+
|
75 |
+
def test_consistency_with_tz_aware_scalar(self):
|
76 |
+
# xef gh-12938
|
77 |
+
# various ways of indexing the same tz-aware scalar
|
78 |
+
df = Series([Timestamp("2016-03-30 14:35:25", tz="Europe/Brussels")]).to_frame()
|
79 |
+
|
80 |
+
df = pd.concat([df, df]).reset_index(drop=True)
|
81 |
+
expected = Timestamp("2016-03-30 14:35:25+0200", tz="Europe/Brussels")
|
82 |
+
|
83 |
+
result = df[0][0]
|
84 |
+
assert result == expected
|
85 |
+
|
86 |
+
result = df.iloc[0, 0]
|
87 |
+
assert result == expected
|
88 |
+
|
89 |
+
result = df.loc[0, 0]
|
90 |
+
assert result == expected
|
91 |
+
|
92 |
+
result = df.iat[0, 0]
|
93 |
+
assert result == expected
|
94 |
+
|
95 |
+
result = df.at[0, 0]
|
96 |
+
assert result == expected
|
97 |
+
|
98 |
+
result = df[0].loc[0]
|
99 |
+
assert result == expected
|
100 |
+
|
101 |
+
result = df[0].at[0]
|
102 |
+
assert result == expected
|
103 |
+
|
104 |
+
def test_indexing_with_datetimeindex_tz(self, indexer_sl):
|
105 |
+
# GH 12050
|
106 |
+
# indexing on a series with a datetimeindex with tz
|
107 |
+
index = date_range("2015-01-01", periods=2, tz="utc")
|
108 |
+
|
109 |
+
ser = Series(range(2), index=index, dtype="int64")
|
110 |
+
|
111 |
+
# list-like indexing
|
112 |
+
|
113 |
+
for sel in (index, list(index)):
|
114 |
+
# getitem
|
115 |
+
result = indexer_sl(ser)[sel]
|
116 |
+
expected = ser.copy()
|
117 |
+
if sel is not index:
|
118 |
+
expected.index = expected.index._with_freq(None)
|
119 |
+
tm.assert_series_equal(result, expected)
|
120 |
+
|
121 |
+
# setitem
|
122 |
+
result = ser.copy()
|
123 |
+
indexer_sl(result)[sel] = 1
|
124 |
+
expected = Series(1, index=index)
|
125 |
+
tm.assert_series_equal(result, expected)
|
126 |
+
|
127 |
+
# single element indexing
|
128 |
+
|
129 |
+
# getitem
|
130 |
+
assert indexer_sl(ser)[index[1]] == 1
|
131 |
+
|
132 |
+
# setitem
|
133 |
+
result = ser.copy()
|
134 |
+
indexer_sl(result)[index[1]] = 5
|
135 |
+
expected = Series([0, 5], index=index)
|
136 |
+
tm.assert_series_equal(result, expected)
|
137 |
+
|
138 |
+
def test_nanosecond_getitem_setitem_with_tz(self):
|
139 |
+
# GH 11679
|
140 |
+
data = ["2016-06-28 08:30:00.123456789"]
|
141 |
+
index = pd.DatetimeIndex(data, dtype="datetime64[ns, America/Chicago]")
|
142 |
+
df = DataFrame({"a": [10]}, index=index)
|
143 |
+
result = df.loc[df.index[0]]
|
144 |
+
expected = Series(10, index=["a"], name=df.index[0])
|
145 |
+
tm.assert_series_equal(result, expected)
|
146 |
+
|
147 |
+
result = df.copy()
|
148 |
+
result.loc[df.index[0], "a"] = -1
|
149 |
+
expected = DataFrame(-1, index=index, columns=["a"])
|
150 |
+
tm.assert_frame_equal(result, expected)
|
151 |
+
|
152 |
+
def test_getitem_str_slice_millisecond_resolution(self, frame_or_series):
|
153 |
+
# GH#33589
|
154 |
+
|
155 |
+
keys = [
|
156 |
+
"2017-10-25T16:25:04.151",
|
157 |
+
"2017-10-25T16:25:04.252",
|
158 |
+
"2017-10-25T16:50:05.237",
|
159 |
+
"2017-10-25T16:50:05.238",
|
160 |
+
]
|
161 |
+
obj = frame_or_series(
|
162 |
+
[1, 2, 3, 4],
|
163 |
+
index=[Timestamp(x) for x in keys],
|
164 |
+
)
|
165 |
+
result = obj[keys[1] : keys[2]]
|
166 |
+
expected = frame_or_series(
|
167 |
+
[2, 3],
|
168 |
+
index=[
|
169 |
+
Timestamp(keys[1]),
|
170 |
+
Timestamp(keys[2]),
|
171 |
+
],
|
172 |
+
)
|
173 |
+
tm.assert_equal(result, expected)
|
174 |
+
|
175 |
+
def test_getitem_pyarrow_index(self, frame_or_series):
|
176 |
+
# GH 53644
|
177 |
+
pytest.importorskip("pyarrow")
|
178 |
+
obj = frame_or_series(
|
179 |
+
range(5),
|
180 |
+
index=date_range("2020", freq="D", periods=5).astype(
|
181 |
+
"timestamp[us][pyarrow]"
|
182 |
+
),
|
183 |
+
)
|
184 |
+
result = obj.loc[obj.index[:-3]]
|
185 |
+
expected = frame_or_series(
|
186 |
+
range(2),
|
187 |
+
index=date_range("2020", freq="D", periods=2).astype(
|
188 |
+
"timestamp[us][pyarrow]"
|
189 |
+
),
|
190 |
+
)
|
191 |
+
tm.assert_equal(result, expected)
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/test_floats.py
ADDED
@@ -0,0 +1,689 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas import (
|
5 |
+
DataFrame,
|
6 |
+
Index,
|
7 |
+
RangeIndex,
|
8 |
+
Series,
|
9 |
+
date_range,
|
10 |
+
period_range,
|
11 |
+
timedelta_range,
|
12 |
+
)
|
13 |
+
import pandas._testing as tm
|
14 |
+
|
15 |
+
|
16 |
+
def gen_obj(klass, index):
|
17 |
+
if klass is Series:
|
18 |
+
obj = Series(np.arange(len(index)), index=index)
|
19 |
+
else:
|
20 |
+
obj = DataFrame(
|
21 |
+
np.random.default_rng(2).standard_normal((len(index), len(index))),
|
22 |
+
index=index,
|
23 |
+
columns=index,
|
24 |
+
)
|
25 |
+
return obj
|
26 |
+
|
27 |
+
|
28 |
+
class TestFloatIndexers:
|
29 |
+
def check(self, result, original, indexer, getitem):
|
30 |
+
"""
|
31 |
+
comparator for results
|
32 |
+
we need to take care if we are indexing on a
|
33 |
+
Series or a frame
|
34 |
+
"""
|
35 |
+
if isinstance(original, Series):
|
36 |
+
expected = original.iloc[indexer]
|
37 |
+
elif getitem:
|
38 |
+
expected = original.iloc[:, indexer]
|
39 |
+
else:
|
40 |
+
expected = original.iloc[indexer]
|
41 |
+
|
42 |
+
tm.assert_almost_equal(result, expected)
|
43 |
+
|
44 |
+
@pytest.mark.parametrize(
|
45 |
+
"index",
|
46 |
+
[
|
47 |
+
Index(list("abcde")),
|
48 |
+
Index(list("abcde"), dtype="category"),
|
49 |
+
date_range("2020-01-01", periods=5),
|
50 |
+
timedelta_range("1 day", periods=5),
|
51 |
+
period_range("2020-01-01", periods=5),
|
52 |
+
],
|
53 |
+
)
|
54 |
+
def test_scalar_non_numeric(self, index, frame_or_series, indexer_sl):
|
55 |
+
# GH 4892
|
56 |
+
# float_indexers should raise exceptions
|
57 |
+
# on appropriate Index types & accessors
|
58 |
+
|
59 |
+
s = gen_obj(frame_or_series, index)
|
60 |
+
|
61 |
+
# getting
|
62 |
+
with pytest.raises(KeyError, match="^3.0$"):
|
63 |
+
indexer_sl(s)[3.0]
|
64 |
+
|
65 |
+
# contains
|
66 |
+
assert 3.0 not in s
|
67 |
+
|
68 |
+
s2 = s.copy()
|
69 |
+
indexer_sl(s2)[3.0] = 10
|
70 |
+
|
71 |
+
if indexer_sl is tm.setitem:
|
72 |
+
assert 3.0 in s2.axes[-1]
|
73 |
+
elif indexer_sl is tm.loc:
|
74 |
+
assert 3.0 in s2.axes[0]
|
75 |
+
else:
|
76 |
+
assert 3.0 not in s2.axes[0]
|
77 |
+
assert 3.0 not in s2.axes[-1]
|
78 |
+
|
79 |
+
@pytest.mark.parametrize(
|
80 |
+
"index",
|
81 |
+
[
|
82 |
+
Index(list("abcde")),
|
83 |
+
Index(list("abcde"), dtype="category"),
|
84 |
+
date_range("2020-01-01", periods=5),
|
85 |
+
timedelta_range("1 day", periods=5),
|
86 |
+
period_range("2020-01-01", periods=5),
|
87 |
+
],
|
88 |
+
)
|
89 |
+
def test_scalar_non_numeric_series_fallback(self, index):
|
90 |
+
# fallsback to position selection, series only
|
91 |
+
s = Series(np.arange(len(index)), index=index)
|
92 |
+
|
93 |
+
msg = "Series.__getitem__ treating keys as positions is deprecated"
|
94 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
95 |
+
s[3]
|
96 |
+
with pytest.raises(KeyError, match="^3.0$"):
|
97 |
+
s[3.0]
|
98 |
+
|
99 |
+
def test_scalar_with_mixed(self, indexer_sl):
|
100 |
+
s2 = Series([1, 2, 3], index=["a", "b", "c"])
|
101 |
+
s3 = Series([1, 2, 3], index=["a", "b", 1.5])
|
102 |
+
|
103 |
+
# lookup in a pure string index with an invalid indexer
|
104 |
+
|
105 |
+
with pytest.raises(KeyError, match="^1.0$"):
|
106 |
+
indexer_sl(s2)[1.0]
|
107 |
+
|
108 |
+
with pytest.raises(KeyError, match=r"^1\.0$"):
|
109 |
+
indexer_sl(s2)[1.0]
|
110 |
+
|
111 |
+
result = indexer_sl(s2)["b"]
|
112 |
+
expected = 2
|
113 |
+
assert result == expected
|
114 |
+
|
115 |
+
# mixed index so we have label
|
116 |
+
# indexing
|
117 |
+
with pytest.raises(KeyError, match="^1.0$"):
|
118 |
+
indexer_sl(s3)[1.0]
|
119 |
+
|
120 |
+
if indexer_sl is not tm.loc:
|
121 |
+
# __getitem__ falls back to positional
|
122 |
+
msg = "Series.__getitem__ treating keys as positions is deprecated"
|
123 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
124 |
+
result = s3[1]
|
125 |
+
expected = 2
|
126 |
+
assert result == expected
|
127 |
+
|
128 |
+
with pytest.raises(KeyError, match=r"^1\.0$"):
|
129 |
+
indexer_sl(s3)[1.0]
|
130 |
+
|
131 |
+
result = indexer_sl(s3)[1.5]
|
132 |
+
expected = 3
|
133 |
+
assert result == expected
|
134 |
+
|
135 |
+
@pytest.mark.parametrize(
|
136 |
+
"index", [Index(np.arange(5), dtype=np.int64), RangeIndex(5)]
|
137 |
+
)
|
138 |
+
def test_scalar_integer(self, index, frame_or_series, indexer_sl):
|
139 |
+
getitem = indexer_sl is not tm.loc
|
140 |
+
|
141 |
+
# test how scalar float indexers work on int indexes
|
142 |
+
|
143 |
+
# integer index
|
144 |
+
i = index
|
145 |
+
obj = gen_obj(frame_or_series, i)
|
146 |
+
|
147 |
+
# coerce to equal int
|
148 |
+
|
149 |
+
result = indexer_sl(obj)[3.0]
|
150 |
+
self.check(result, obj, 3, getitem)
|
151 |
+
|
152 |
+
if isinstance(obj, Series):
|
153 |
+
|
154 |
+
def compare(x, y):
|
155 |
+
assert x == y
|
156 |
+
|
157 |
+
expected = 100
|
158 |
+
else:
|
159 |
+
compare = tm.assert_series_equal
|
160 |
+
if getitem:
|
161 |
+
expected = Series(100, index=range(len(obj)), name=3)
|
162 |
+
else:
|
163 |
+
expected = Series(100.0, index=range(len(obj)), name=3)
|
164 |
+
|
165 |
+
s2 = obj.copy()
|
166 |
+
indexer_sl(s2)[3.0] = 100
|
167 |
+
|
168 |
+
result = indexer_sl(s2)[3.0]
|
169 |
+
compare(result, expected)
|
170 |
+
|
171 |
+
result = indexer_sl(s2)[3]
|
172 |
+
compare(result, expected)
|
173 |
+
|
174 |
+
@pytest.mark.parametrize(
|
175 |
+
"index", [Index(np.arange(5), dtype=np.int64), RangeIndex(5)]
|
176 |
+
)
|
177 |
+
def test_scalar_integer_contains_float(self, index, frame_or_series):
|
178 |
+
# contains
|
179 |
+
# integer index
|
180 |
+
obj = gen_obj(frame_or_series, index)
|
181 |
+
|
182 |
+
# coerce to equal int
|
183 |
+
assert 3.0 in obj
|
184 |
+
|
185 |
+
def test_scalar_float(self, frame_or_series):
|
186 |
+
# scalar float indexers work on a float index
|
187 |
+
index = Index(np.arange(5.0))
|
188 |
+
s = gen_obj(frame_or_series, index)
|
189 |
+
|
190 |
+
# assert all operations except for iloc are ok
|
191 |
+
indexer = index[3]
|
192 |
+
for idxr in [tm.loc, tm.setitem]:
|
193 |
+
getitem = idxr is not tm.loc
|
194 |
+
|
195 |
+
# getting
|
196 |
+
result = idxr(s)[indexer]
|
197 |
+
self.check(result, s, 3, getitem)
|
198 |
+
|
199 |
+
# setting
|
200 |
+
s2 = s.copy()
|
201 |
+
|
202 |
+
result = idxr(s2)[indexer]
|
203 |
+
self.check(result, s, 3, getitem)
|
204 |
+
|
205 |
+
# random float is a KeyError
|
206 |
+
with pytest.raises(KeyError, match=r"^3\.5$"):
|
207 |
+
idxr(s)[3.5]
|
208 |
+
|
209 |
+
# contains
|
210 |
+
assert 3.0 in s
|
211 |
+
|
212 |
+
# iloc succeeds with an integer
|
213 |
+
expected = s.iloc[3]
|
214 |
+
s2 = s.copy()
|
215 |
+
|
216 |
+
s2.iloc[3] = expected
|
217 |
+
result = s2.iloc[3]
|
218 |
+
self.check(result, s, 3, False)
|
219 |
+
|
220 |
+
@pytest.mark.parametrize(
|
221 |
+
"index",
|
222 |
+
[
|
223 |
+
Index(list("abcde"), dtype=object),
|
224 |
+
date_range("2020-01-01", periods=5),
|
225 |
+
timedelta_range("1 day", periods=5),
|
226 |
+
period_range("2020-01-01", periods=5),
|
227 |
+
],
|
228 |
+
)
|
229 |
+
@pytest.mark.parametrize("idx", [slice(3.0, 4), slice(3, 4.0), slice(3.0, 4.0)])
|
230 |
+
def test_slice_non_numeric(self, index, idx, frame_or_series, indexer_sli):
|
231 |
+
# GH 4892
|
232 |
+
# float_indexers should raise exceptions
|
233 |
+
# on appropriate Index types & accessors
|
234 |
+
|
235 |
+
s = gen_obj(frame_or_series, index)
|
236 |
+
|
237 |
+
# getitem
|
238 |
+
if indexer_sli is tm.iloc:
|
239 |
+
msg = (
|
240 |
+
"cannot do positional indexing "
|
241 |
+
rf"on {type(index).__name__} with these indexers \[(3|4)\.0\] of "
|
242 |
+
"type float"
|
243 |
+
)
|
244 |
+
else:
|
245 |
+
msg = (
|
246 |
+
"cannot do slice indexing "
|
247 |
+
rf"on {type(index).__name__} with these indexers "
|
248 |
+
r"\[(3|4)(\.0)?\] "
|
249 |
+
r"of type (float|int)"
|
250 |
+
)
|
251 |
+
with pytest.raises(TypeError, match=msg):
|
252 |
+
indexer_sli(s)[idx]
|
253 |
+
|
254 |
+
# setitem
|
255 |
+
if indexer_sli is tm.iloc:
|
256 |
+
# otherwise we keep the same message as above
|
257 |
+
msg = "slice indices must be integers or None or have an __index__ method"
|
258 |
+
with pytest.raises(TypeError, match=msg):
|
259 |
+
indexer_sli(s)[idx] = 0
|
260 |
+
|
261 |
+
def test_slice_integer(self):
|
262 |
+
# same as above, but for Integer based indexes
|
263 |
+
# these coerce to a like integer
|
264 |
+
# oob indicates if we are out of bounds
|
265 |
+
# of positional indexing
|
266 |
+
for index, oob in [
|
267 |
+
(Index(np.arange(5, dtype=np.int64)), False),
|
268 |
+
(RangeIndex(5), False),
|
269 |
+
(Index(np.arange(5, dtype=np.int64) + 10), True),
|
270 |
+
]:
|
271 |
+
# s is an in-range index
|
272 |
+
s = Series(range(5), index=index)
|
273 |
+
|
274 |
+
# getitem
|
275 |
+
for idx in [slice(3.0, 4), slice(3, 4.0), slice(3.0, 4.0)]:
|
276 |
+
result = s.loc[idx]
|
277 |
+
|
278 |
+
# these are all label indexing
|
279 |
+
# except getitem which is positional
|
280 |
+
# empty
|
281 |
+
if oob:
|
282 |
+
indexer = slice(0, 0)
|
283 |
+
else:
|
284 |
+
indexer = slice(3, 5)
|
285 |
+
self.check(result, s, indexer, False)
|
286 |
+
|
287 |
+
# getitem out-of-bounds
|
288 |
+
for idx in [slice(-6, 6), slice(-6.0, 6.0)]:
|
289 |
+
result = s.loc[idx]
|
290 |
+
|
291 |
+
# these are all label indexing
|
292 |
+
# except getitem which is positional
|
293 |
+
# empty
|
294 |
+
if oob:
|
295 |
+
indexer = slice(0, 0)
|
296 |
+
else:
|
297 |
+
indexer = slice(-6, 6)
|
298 |
+
self.check(result, s, indexer, False)
|
299 |
+
|
300 |
+
# positional indexing
|
301 |
+
msg = (
|
302 |
+
"cannot do slice indexing "
|
303 |
+
rf"on {type(index).__name__} with these indexers \[-6\.0\] of "
|
304 |
+
"type float"
|
305 |
+
)
|
306 |
+
with pytest.raises(TypeError, match=msg):
|
307 |
+
s[slice(-6.0, 6.0)]
|
308 |
+
|
309 |
+
# getitem odd floats
|
310 |
+
for idx, res1 in [
|
311 |
+
(slice(2.5, 4), slice(3, 5)),
|
312 |
+
(slice(2, 3.5), slice(2, 4)),
|
313 |
+
(slice(2.5, 3.5), slice(3, 4)),
|
314 |
+
]:
|
315 |
+
result = s.loc[idx]
|
316 |
+
if oob:
|
317 |
+
res = slice(0, 0)
|
318 |
+
else:
|
319 |
+
res = res1
|
320 |
+
|
321 |
+
self.check(result, s, res, False)
|
322 |
+
|
323 |
+
# positional indexing
|
324 |
+
msg = (
|
325 |
+
"cannot do slice indexing "
|
326 |
+
rf"on {type(index).__name__} with these indexers \[(2|3)\.5\] of "
|
327 |
+
"type float"
|
328 |
+
)
|
329 |
+
with pytest.raises(TypeError, match=msg):
|
330 |
+
s[idx]
|
331 |
+
|
332 |
+
@pytest.mark.parametrize("idx", [slice(2, 4.0), slice(2.0, 4), slice(2.0, 4.0)])
|
333 |
+
def test_integer_positional_indexing(self, idx):
|
334 |
+
"""make sure that we are raising on positional indexing
|
335 |
+
w.r.t. an integer index
|
336 |
+
"""
|
337 |
+
s = Series(range(2, 6), index=range(2, 6))
|
338 |
+
|
339 |
+
result = s[2:4]
|
340 |
+
expected = s.iloc[2:4]
|
341 |
+
tm.assert_series_equal(result, expected)
|
342 |
+
|
343 |
+
klass = RangeIndex
|
344 |
+
msg = (
|
345 |
+
"cannot do (slice|positional) indexing "
|
346 |
+
rf"on {klass.__name__} with these indexers \[(2|4)\.0\] of "
|
347 |
+
"type float"
|
348 |
+
)
|
349 |
+
with pytest.raises(TypeError, match=msg):
|
350 |
+
s[idx]
|
351 |
+
with pytest.raises(TypeError, match=msg):
|
352 |
+
s.iloc[idx]
|
353 |
+
|
354 |
+
@pytest.mark.parametrize(
|
355 |
+
"index", [Index(np.arange(5), dtype=np.int64), RangeIndex(5)]
|
356 |
+
)
|
357 |
+
def test_slice_integer_frame_getitem(self, index):
|
358 |
+
# similar to above, but on the getitem dim (of a DataFrame)
|
359 |
+
s = DataFrame(np.random.default_rng(2).standard_normal((5, 2)), index=index)
|
360 |
+
|
361 |
+
# getitem
|
362 |
+
for idx in [slice(0.0, 1), slice(0, 1.0), slice(0.0, 1.0)]:
|
363 |
+
result = s.loc[idx]
|
364 |
+
indexer = slice(0, 2)
|
365 |
+
self.check(result, s, indexer, False)
|
366 |
+
|
367 |
+
# positional indexing
|
368 |
+
msg = (
|
369 |
+
"cannot do slice indexing "
|
370 |
+
rf"on {type(index).__name__} with these indexers \[(0|1)\.0\] of "
|
371 |
+
"type float"
|
372 |
+
)
|
373 |
+
with pytest.raises(TypeError, match=msg):
|
374 |
+
s[idx]
|
375 |
+
|
376 |
+
# getitem out-of-bounds
|
377 |
+
for idx in [slice(-10, 10), slice(-10.0, 10.0)]:
|
378 |
+
result = s.loc[idx]
|
379 |
+
self.check(result, s, slice(-10, 10), True)
|
380 |
+
|
381 |
+
# positional indexing
|
382 |
+
msg = (
|
383 |
+
"cannot do slice indexing "
|
384 |
+
rf"on {type(index).__name__} with these indexers \[-10\.0\] of "
|
385 |
+
"type float"
|
386 |
+
)
|
387 |
+
with pytest.raises(TypeError, match=msg):
|
388 |
+
s[slice(-10.0, 10.0)]
|
389 |
+
|
390 |
+
# getitem odd floats
|
391 |
+
for idx, res in [
|
392 |
+
(slice(0.5, 1), slice(1, 2)),
|
393 |
+
(slice(0, 0.5), slice(0, 1)),
|
394 |
+
(slice(0.5, 1.5), slice(1, 2)),
|
395 |
+
]:
|
396 |
+
result = s.loc[idx]
|
397 |
+
self.check(result, s, res, False)
|
398 |
+
|
399 |
+
# positional indexing
|
400 |
+
msg = (
|
401 |
+
"cannot do slice indexing "
|
402 |
+
rf"on {type(index).__name__} with these indexers \[0\.5\] of "
|
403 |
+
"type float"
|
404 |
+
)
|
405 |
+
with pytest.raises(TypeError, match=msg):
|
406 |
+
s[idx]
|
407 |
+
|
408 |
+
@pytest.mark.parametrize("idx", [slice(3.0, 4), slice(3, 4.0), slice(3.0, 4.0)])
|
409 |
+
@pytest.mark.parametrize(
|
410 |
+
"index", [Index(np.arange(5), dtype=np.int64), RangeIndex(5)]
|
411 |
+
)
|
412 |
+
def test_float_slice_getitem_with_integer_index_raises(self, idx, index):
|
413 |
+
# similar to above, but on the getitem dim (of a DataFrame)
|
414 |
+
s = DataFrame(np.random.default_rng(2).standard_normal((5, 2)), index=index)
|
415 |
+
|
416 |
+
# setitem
|
417 |
+
sc = s.copy()
|
418 |
+
sc.loc[idx] = 0
|
419 |
+
result = sc.loc[idx].values.ravel()
|
420 |
+
assert (result == 0).all()
|
421 |
+
|
422 |
+
# positional indexing
|
423 |
+
msg = (
|
424 |
+
"cannot do slice indexing "
|
425 |
+
rf"on {type(index).__name__} with these indexers \[(3|4)\.0\] of "
|
426 |
+
"type float"
|
427 |
+
)
|
428 |
+
with pytest.raises(TypeError, match=msg):
|
429 |
+
s[idx] = 0
|
430 |
+
|
431 |
+
with pytest.raises(TypeError, match=msg):
|
432 |
+
s[idx]
|
433 |
+
|
434 |
+
@pytest.mark.parametrize("idx", [slice(3.0, 4), slice(3, 4.0), slice(3.0, 4.0)])
|
435 |
+
def test_slice_float(self, idx, frame_or_series, indexer_sl):
|
436 |
+
# same as above, but for floats
|
437 |
+
index = Index(np.arange(5.0)) + 0.1
|
438 |
+
s = gen_obj(frame_or_series, index)
|
439 |
+
|
440 |
+
expected = s.iloc[3:4]
|
441 |
+
|
442 |
+
# getitem
|
443 |
+
result = indexer_sl(s)[idx]
|
444 |
+
assert isinstance(result, type(s))
|
445 |
+
tm.assert_equal(result, expected)
|
446 |
+
|
447 |
+
# setitem
|
448 |
+
s2 = s.copy()
|
449 |
+
indexer_sl(s2)[idx] = 0
|
450 |
+
result = indexer_sl(s2)[idx].values.ravel()
|
451 |
+
assert (result == 0).all()
|
452 |
+
|
453 |
+
def test_floating_index_doc_example(self):
|
454 |
+
index = Index([1.5, 2, 3, 4.5, 5])
|
455 |
+
s = Series(range(5), index=index)
|
456 |
+
assert s[3] == 2
|
457 |
+
assert s.loc[3] == 2
|
458 |
+
assert s.iloc[3] == 3
|
459 |
+
|
460 |
+
def test_floating_misc(self, indexer_sl):
|
461 |
+
# related 236
|
462 |
+
# scalar/slicing of a float index
|
463 |
+
s = Series(np.arange(5), index=np.arange(5) * 2.5, dtype=np.int64)
|
464 |
+
|
465 |
+
# label based slicing
|
466 |
+
result = indexer_sl(s)[1.0:3.0]
|
467 |
+
expected = Series(1, index=[2.5])
|
468 |
+
tm.assert_series_equal(result, expected)
|
469 |
+
|
470 |
+
# exact indexing when found
|
471 |
+
|
472 |
+
result = indexer_sl(s)[5.0]
|
473 |
+
assert result == 2
|
474 |
+
|
475 |
+
result = indexer_sl(s)[5]
|
476 |
+
assert result == 2
|
477 |
+
|
478 |
+
# value not found (and no fallbacking at all)
|
479 |
+
|
480 |
+
# scalar integers
|
481 |
+
with pytest.raises(KeyError, match=r"^4$"):
|
482 |
+
indexer_sl(s)[4]
|
483 |
+
|
484 |
+
# fancy floats/integers create the correct entry (as nan)
|
485 |
+
# fancy tests
|
486 |
+
expected = Series([2, 0], index=Index([5.0, 0.0], dtype=np.float64))
|
487 |
+
for fancy_idx in [[5.0, 0.0], np.array([5.0, 0.0])]: # float
|
488 |
+
tm.assert_series_equal(indexer_sl(s)[fancy_idx], expected)
|
489 |
+
|
490 |
+
expected = Series([2, 0], index=Index([5, 0], dtype="float64"))
|
491 |
+
for fancy_idx in [[5, 0], np.array([5, 0])]:
|
492 |
+
tm.assert_series_equal(indexer_sl(s)[fancy_idx], expected)
|
493 |
+
|
494 |
+
warn = FutureWarning if indexer_sl is tm.setitem else None
|
495 |
+
msg = r"The behavior of obj\[i:j\] with a float-dtype index"
|
496 |
+
|
497 |
+
# all should return the same as we are slicing 'the same'
|
498 |
+
with tm.assert_produces_warning(warn, match=msg):
|
499 |
+
result1 = indexer_sl(s)[2:5]
|
500 |
+
result2 = indexer_sl(s)[2.0:5.0]
|
501 |
+
result3 = indexer_sl(s)[2.0:5]
|
502 |
+
result4 = indexer_sl(s)[2.1:5]
|
503 |
+
tm.assert_series_equal(result1, result2)
|
504 |
+
tm.assert_series_equal(result1, result3)
|
505 |
+
tm.assert_series_equal(result1, result4)
|
506 |
+
|
507 |
+
expected = Series([1, 2], index=[2.5, 5.0])
|
508 |
+
with tm.assert_produces_warning(warn, match=msg):
|
509 |
+
result = indexer_sl(s)[2:5]
|
510 |
+
|
511 |
+
tm.assert_series_equal(result, expected)
|
512 |
+
|
513 |
+
# list selection
|
514 |
+
result1 = indexer_sl(s)[[0.0, 5, 10]]
|
515 |
+
result2 = s.iloc[[0, 2, 4]]
|
516 |
+
tm.assert_series_equal(result1, result2)
|
517 |
+
|
518 |
+
with pytest.raises(KeyError, match="not in index"):
|
519 |
+
indexer_sl(s)[[1.6, 5, 10]]
|
520 |
+
|
521 |
+
with pytest.raises(KeyError, match="not in index"):
|
522 |
+
indexer_sl(s)[[0, 1, 2]]
|
523 |
+
|
524 |
+
result = indexer_sl(s)[[2.5, 5]]
|
525 |
+
tm.assert_series_equal(result, Series([1, 2], index=[2.5, 5.0]))
|
526 |
+
|
527 |
+
result = indexer_sl(s)[[2.5]]
|
528 |
+
tm.assert_series_equal(result, Series([1], index=[2.5]))
|
529 |
+
|
530 |
+
def test_floatindex_slicing_bug(self, float_numpy_dtype):
|
531 |
+
# GH 5557, related to slicing a float index
|
532 |
+
dtype = float_numpy_dtype
|
533 |
+
ser = {
|
534 |
+
256: 2321.0,
|
535 |
+
1: 78.0,
|
536 |
+
2: 2716.0,
|
537 |
+
3: 0.0,
|
538 |
+
4: 369.0,
|
539 |
+
5: 0.0,
|
540 |
+
6: 269.0,
|
541 |
+
7: 0.0,
|
542 |
+
8: 0.0,
|
543 |
+
9: 0.0,
|
544 |
+
10: 3536.0,
|
545 |
+
11: 0.0,
|
546 |
+
12: 24.0,
|
547 |
+
13: 0.0,
|
548 |
+
14: 931.0,
|
549 |
+
15: 0.0,
|
550 |
+
16: 101.0,
|
551 |
+
17: 78.0,
|
552 |
+
18: 9643.0,
|
553 |
+
19: 0.0,
|
554 |
+
20: 0.0,
|
555 |
+
21: 0.0,
|
556 |
+
22: 63761.0,
|
557 |
+
23: 0.0,
|
558 |
+
24: 446.0,
|
559 |
+
25: 0.0,
|
560 |
+
26: 34773.0,
|
561 |
+
27: 0.0,
|
562 |
+
28: 729.0,
|
563 |
+
29: 78.0,
|
564 |
+
30: 0.0,
|
565 |
+
31: 0.0,
|
566 |
+
32: 3374.0,
|
567 |
+
33: 0.0,
|
568 |
+
34: 1391.0,
|
569 |
+
35: 0.0,
|
570 |
+
36: 361.0,
|
571 |
+
37: 0.0,
|
572 |
+
38: 61808.0,
|
573 |
+
39: 0.0,
|
574 |
+
40: 0.0,
|
575 |
+
41: 0.0,
|
576 |
+
42: 6677.0,
|
577 |
+
43: 0.0,
|
578 |
+
44: 802.0,
|
579 |
+
45: 0.0,
|
580 |
+
46: 2691.0,
|
581 |
+
47: 0.0,
|
582 |
+
48: 3582.0,
|
583 |
+
49: 0.0,
|
584 |
+
50: 734.0,
|
585 |
+
51: 0.0,
|
586 |
+
52: 627.0,
|
587 |
+
53: 70.0,
|
588 |
+
54: 2584.0,
|
589 |
+
55: 0.0,
|
590 |
+
56: 324.0,
|
591 |
+
57: 0.0,
|
592 |
+
58: 605.0,
|
593 |
+
59: 0.0,
|
594 |
+
60: 0.0,
|
595 |
+
61: 0.0,
|
596 |
+
62: 3989.0,
|
597 |
+
63: 10.0,
|
598 |
+
64: 42.0,
|
599 |
+
65: 0.0,
|
600 |
+
66: 904.0,
|
601 |
+
67: 0.0,
|
602 |
+
68: 88.0,
|
603 |
+
69: 70.0,
|
604 |
+
70: 8172.0,
|
605 |
+
71: 0.0,
|
606 |
+
72: 0.0,
|
607 |
+
73: 0.0,
|
608 |
+
74: 64902.0,
|
609 |
+
75: 0.0,
|
610 |
+
76: 347.0,
|
611 |
+
77: 0.0,
|
612 |
+
78: 36605.0,
|
613 |
+
79: 0.0,
|
614 |
+
80: 379.0,
|
615 |
+
81: 70.0,
|
616 |
+
82: 0.0,
|
617 |
+
83: 0.0,
|
618 |
+
84: 3001.0,
|
619 |
+
85: 0.0,
|
620 |
+
86: 1630.0,
|
621 |
+
87: 7.0,
|
622 |
+
88: 364.0,
|
623 |
+
89: 0.0,
|
624 |
+
90: 67404.0,
|
625 |
+
91: 9.0,
|
626 |
+
92: 0.0,
|
627 |
+
93: 0.0,
|
628 |
+
94: 7685.0,
|
629 |
+
95: 0.0,
|
630 |
+
96: 1017.0,
|
631 |
+
97: 0.0,
|
632 |
+
98: 2831.0,
|
633 |
+
99: 0.0,
|
634 |
+
100: 2963.0,
|
635 |
+
101: 0.0,
|
636 |
+
102: 854.0,
|
637 |
+
103: 0.0,
|
638 |
+
104: 0.0,
|
639 |
+
105: 0.0,
|
640 |
+
106: 0.0,
|
641 |
+
107: 0.0,
|
642 |
+
108: 0.0,
|
643 |
+
109: 0.0,
|
644 |
+
110: 0.0,
|
645 |
+
111: 0.0,
|
646 |
+
112: 0.0,
|
647 |
+
113: 0.0,
|
648 |
+
114: 0.0,
|
649 |
+
115: 0.0,
|
650 |
+
116: 0.0,
|
651 |
+
117: 0.0,
|
652 |
+
118: 0.0,
|
653 |
+
119: 0.0,
|
654 |
+
120: 0.0,
|
655 |
+
121: 0.0,
|
656 |
+
122: 0.0,
|
657 |
+
123: 0.0,
|
658 |
+
124: 0.0,
|
659 |
+
125: 0.0,
|
660 |
+
126: 67744.0,
|
661 |
+
127: 22.0,
|
662 |
+
128: 264.0,
|
663 |
+
129: 0.0,
|
664 |
+
260: 197.0,
|
665 |
+
268: 0.0,
|
666 |
+
265: 0.0,
|
667 |
+
269: 0.0,
|
668 |
+
261: 0.0,
|
669 |
+
266: 1198.0,
|
670 |
+
267: 0.0,
|
671 |
+
262: 2629.0,
|
672 |
+
258: 775.0,
|
673 |
+
257: 0.0,
|
674 |
+
263: 0.0,
|
675 |
+
259: 0.0,
|
676 |
+
264: 163.0,
|
677 |
+
250: 10326.0,
|
678 |
+
251: 0.0,
|
679 |
+
252: 1228.0,
|
680 |
+
253: 0.0,
|
681 |
+
254: 2769.0,
|
682 |
+
255: 0.0,
|
683 |
+
}
|
684 |
+
|
685 |
+
# smoke test for the repr
|
686 |
+
s = Series(ser, dtype=dtype)
|
687 |
+
result = s.value_counts()
|
688 |
+
assert result.index.dtype == dtype
|
689 |
+
str(result)
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/test_iat.py
ADDED
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
|
3 |
+
from pandas import (
|
4 |
+
DataFrame,
|
5 |
+
Series,
|
6 |
+
period_range,
|
7 |
+
)
|
8 |
+
import pandas._testing as tm
|
9 |
+
|
10 |
+
|
11 |
+
def test_iat(float_frame):
|
12 |
+
for i, row in enumerate(float_frame.index):
|
13 |
+
for j, col in enumerate(float_frame.columns):
|
14 |
+
result = float_frame.iat[i, j]
|
15 |
+
expected = float_frame.at[row, col]
|
16 |
+
assert result == expected
|
17 |
+
|
18 |
+
|
19 |
+
def test_iat_duplicate_columns():
|
20 |
+
# https://github.com/pandas-dev/pandas/issues/11754
|
21 |
+
df = DataFrame([[1, 2]], columns=["x", "x"])
|
22 |
+
assert df.iat[0, 0] == 1
|
23 |
+
|
24 |
+
|
25 |
+
def test_iat_getitem_series_with_period_index():
|
26 |
+
# GH#4390, iat incorrectly indexing
|
27 |
+
index = period_range("1/1/2001", periods=10)
|
28 |
+
ser = Series(np.random.default_rng(2).standard_normal(10), index=index)
|
29 |
+
expected = ser[index[0]]
|
30 |
+
result = ser.iat[0]
|
31 |
+
assert expected == result
|
32 |
+
|
33 |
+
|
34 |
+
def test_iat_setitem_item_cache_cleared(
|
35 |
+
indexer_ial, using_copy_on_write, warn_copy_on_write
|
36 |
+
):
|
37 |
+
# GH#45684
|
38 |
+
data = {"x": np.arange(8, dtype=np.int64), "y": np.int64(0)}
|
39 |
+
df = DataFrame(data).copy()
|
40 |
+
ser = df["y"]
|
41 |
+
|
42 |
+
# previously this iat setting would split the block and fail to clear
|
43 |
+
# the item_cache.
|
44 |
+
with tm.assert_cow_warning(warn_copy_on_write):
|
45 |
+
indexer_ial(df)[7, 0] = 9999
|
46 |
+
|
47 |
+
with tm.assert_cow_warning(warn_copy_on_write):
|
48 |
+
indexer_ial(df)[7, 1] = 1234
|
49 |
+
|
50 |
+
assert df.iat[7, 1] == 1234
|
51 |
+
if not using_copy_on_write:
|
52 |
+
assert ser.iloc[-1] == 1234
|
53 |
+
assert df.iloc[-1, -1] == 1234
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/test_iloc.py
ADDED
@@ -0,0 +1,1478 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" test positional based indexing with iloc """
|
2 |
+
|
3 |
+
from datetime import datetime
|
4 |
+
import re
|
5 |
+
|
6 |
+
import numpy as np
|
7 |
+
import pytest
|
8 |
+
|
9 |
+
from pandas.errors import IndexingError
|
10 |
+
import pandas.util._test_decorators as td
|
11 |
+
|
12 |
+
from pandas import (
|
13 |
+
NA,
|
14 |
+
Categorical,
|
15 |
+
CategoricalDtype,
|
16 |
+
DataFrame,
|
17 |
+
Index,
|
18 |
+
Interval,
|
19 |
+
NaT,
|
20 |
+
Series,
|
21 |
+
Timestamp,
|
22 |
+
array,
|
23 |
+
concat,
|
24 |
+
date_range,
|
25 |
+
interval_range,
|
26 |
+
isna,
|
27 |
+
to_datetime,
|
28 |
+
)
|
29 |
+
import pandas._testing as tm
|
30 |
+
from pandas.api.types import is_scalar
|
31 |
+
from pandas.tests.indexing.common import check_indexing_smoketest_or_raises
|
32 |
+
|
33 |
+
# We pass through the error message from numpy
|
34 |
+
_slice_iloc_msg = re.escape(
|
35 |
+
"only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) "
|
36 |
+
"and integer or boolean arrays are valid indices"
|
37 |
+
)
|
38 |
+
|
39 |
+
|
40 |
+
class TestiLoc:
|
41 |
+
@pytest.mark.parametrize("key", [2, -1, [0, 1, 2]])
|
42 |
+
@pytest.mark.parametrize("kind", ["series", "frame"])
|
43 |
+
@pytest.mark.parametrize(
|
44 |
+
"col",
|
45 |
+
["labels", "mixed", "ts", "floats", "empty"],
|
46 |
+
)
|
47 |
+
def test_iloc_getitem_int_and_list_int(self, key, kind, col, request):
|
48 |
+
obj = request.getfixturevalue(f"{kind}_{col}")
|
49 |
+
check_indexing_smoketest_or_raises(
|
50 |
+
obj,
|
51 |
+
"iloc",
|
52 |
+
key,
|
53 |
+
fails=IndexError,
|
54 |
+
)
|
55 |
+
|
56 |
+
# array of ints (GH5006), make sure that a single indexer is returning
|
57 |
+
# the correct type
|
58 |
+
|
59 |
+
|
60 |
+
class TestiLocBaseIndependent:
|
61 |
+
"""Tests Independent Of Base Class"""
|
62 |
+
|
63 |
+
@pytest.mark.parametrize(
|
64 |
+
"key",
|
65 |
+
[
|
66 |
+
slice(None),
|
67 |
+
slice(3),
|
68 |
+
range(3),
|
69 |
+
[0, 1, 2],
|
70 |
+
Index(range(3)),
|
71 |
+
np.asarray([0, 1, 2]),
|
72 |
+
],
|
73 |
+
)
|
74 |
+
@pytest.mark.parametrize("indexer", [tm.loc, tm.iloc])
|
75 |
+
def test_iloc_setitem_fullcol_categorical(self, indexer, key, using_array_manager):
|
76 |
+
frame = DataFrame({0: range(3)}, dtype=object)
|
77 |
+
|
78 |
+
cat = Categorical(["alpha", "beta", "gamma"])
|
79 |
+
|
80 |
+
if not using_array_manager:
|
81 |
+
assert frame._mgr.blocks[0]._can_hold_element(cat)
|
82 |
+
|
83 |
+
df = frame.copy()
|
84 |
+
orig_vals = df.values
|
85 |
+
|
86 |
+
indexer(df)[key, 0] = cat
|
87 |
+
|
88 |
+
expected = DataFrame({0: cat}).astype(object)
|
89 |
+
if not using_array_manager:
|
90 |
+
assert np.shares_memory(df[0].values, orig_vals)
|
91 |
+
|
92 |
+
tm.assert_frame_equal(df, expected)
|
93 |
+
|
94 |
+
# check we dont have a view on cat (may be undesired GH#39986)
|
95 |
+
df.iloc[0, 0] = "gamma"
|
96 |
+
assert cat[0] != "gamma"
|
97 |
+
|
98 |
+
# pre-2.0 with mixed dataframe ("split" path) we always overwrote the
|
99 |
+
# column. as of 2.0 we correctly write "into" the column, so
|
100 |
+
# we retain the object dtype.
|
101 |
+
frame = DataFrame({0: np.array([0, 1, 2], dtype=object), 1: range(3)})
|
102 |
+
df = frame.copy()
|
103 |
+
indexer(df)[key, 0] = cat
|
104 |
+
expected = DataFrame({0: Series(cat.astype(object), dtype=object), 1: range(3)})
|
105 |
+
tm.assert_frame_equal(df, expected)
|
106 |
+
|
107 |
+
@pytest.mark.parametrize("box", [array, Series])
|
108 |
+
def test_iloc_setitem_ea_inplace(self, frame_or_series, box, using_copy_on_write):
|
109 |
+
# GH#38952 Case with not setting a full column
|
110 |
+
# IntegerArray without NAs
|
111 |
+
arr = array([1, 2, 3, 4])
|
112 |
+
obj = frame_or_series(arr.to_numpy("i8"))
|
113 |
+
|
114 |
+
if frame_or_series is Series:
|
115 |
+
values = obj.values
|
116 |
+
else:
|
117 |
+
values = obj._mgr.arrays[0]
|
118 |
+
|
119 |
+
if frame_or_series is Series:
|
120 |
+
obj.iloc[:2] = box(arr[2:])
|
121 |
+
else:
|
122 |
+
obj.iloc[:2, 0] = box(arr[2:])
|
123 |
+
|
124 |
+
expected = frame_or_series(np.array([3, 4, 3, 4], dtype="i8"))
|
125 |
+
tm.assert_equal(obj, expected)
|
126 |
+
|
127 |
+
# Check that we are actually in-place
|
128 |
+
if frame_or_series is Series:
|
129 |
+
if using_copy_on_write:
|
130 |
+
assert obj.values is not values
|
131 |
+
assert np.shares_memory(obj.values, values)
|
132 |
+
else:
|
133 |
+
assert obj.values is values
|
134 |
+
else:
|
135 |
+
assert np.shares_memory(obj[0].values, values)
|
136 |
+
|
137 |
+
def test_is_scalar_access(self):
|
138 |
+
# GH#32085 index with duplicates doesn't matter for _is_scalar_access
|
139 |
+
index = Index([1, 2, 1])
|
140 |
+
ser = Series(range(3), index=index)
|
141 |
+
|
142 |
+
assert ser.iloc._is_scalar_access((1,))
|
143 |
+
|
144 |
+
df = ser.to_frame()
|
145 |
+
assert df.iloc._is_scalar_access((1, 0))
|
146 |
+
|
147 |
+
def test_iloc_exceeds_bounds(self):
|
148 |
+
# GH6296
|
149 |
+
# iloc should allow indexers that exceed the bounds
|
150 |
+
df = DataFrame(np.random.default_rng(2).random((20, 5)), columns=list("ABCDE"))
|
151 |
+
|
152 |
+
# lists of positions should raise IndexError!
|
153 |
+
msg = "positional indexers are out-of-bounds"
|
154 |
+
with pytest.raises(IndexError, match=msg):
|
155 |
+
df.iloc[:, [0, 1, 2, 3, 4, 5]]
|
156 |
+
with pytest.raises(IndexError, match=msg):
|
157 |
+
df.iloc[[1, 30]]
|
158 |
+
with pytest.raises(IndexError, match=msg):
|
159 |
+
df.iloc[[1, -30]]
|
160 |
+
with pytest.raises(IndexError, match=msg):
|
161 |
+
df.iloc[[100]]
|
162 |
+
|
163 |
+
s = df["A"]
|
164 |
+
with pytest.raises(IndexError, match=msg):
|
165 |
+
s.iloc[[100]]
|
166 |
+
with pytest.raises(IndexError, match=msg):
|
167 |
+
s.iloc[[-100]]
|
168 |
+
|
169 |
+
# still raise on a single indexer
|
170 |
+
msg = "single positional indexer is out-of-bounds"
|
171 |
+
with pytest.raises(IndexError, match=msg):
|
172 |
+
df.iloc[30]
|
173 |
+
with pytest.raises(IndexError, match=msg):
|
174 |
+
df.iloc[-30]
|
175 |
+
|
176 |
+
# GH10779
|
177 |
+
# single positive/negative indexer exceeding Series bounds should raise
|
178 |
+
# an IndexError
|
179 |
+
with pytest.raises(IndexError, match=msg):
|
180 |
+
s.iloc[30]
|
181 |
+
with pytest.raises(IndexError, match=msg):
|
182 |
+
s.iloc[-30]
|
183 |
+
|
184 |
+
# slices are ok
|
185 |
+
result = df.iloc[:, 4:10] # 0 < start < len < stop
|
186 |
+
expected = df.iloc[:, 4:]
|
187 |
+
tm.assert_frame_equal(result, expected)
|
188 |
+
|
189 |
+
result = df.iloc[:, -4:-10] # stop < 0 < start < len
|
190 |
+
expected = df.iloc[:, :0]
|
191 |
+
tm.assert_frame_equal(result, expected)
|
192 |
+
|
193 |
+
result = df.iloc[:, 10:4:-1] # 0 < stop < len < start (down)
|
194 |
+
expected = df.iloc[:, :4:-1]
|
195 |
+
tm.assert_frame_equal(result, expected)
|
196 |
+
|
197 |
+
result = df.iloc[:, 4:-10:-1] # stop < 0 < start < len (down)
|
198 |
+
expected = df.iloc[:, 4::-1]
|
199 |
+
tm.assert_frame_equal(result, expected)
|
200 |
+
|
201 |
+
result = df.iloc[:, -10:4] # start < 0 < stop < len
|
202 |
+
expected = df.iloc[:, :4]
|
203 |
+
tm.assert_frame_equal(result, expected)
|
204 |
+
|
205 |
+
result = df.iloc[:, 10:4] # 0 < stop < len < start
|
206 |
+
expected = df.iloc[:, :0]
|
207 |
+
tm.assert_frame_equal(result, expected)
|
208 |
+
|
209 |
+
result = df.iloc[:, -10:-11:-1] # stop < start < 0 < len (down)
|
210 |
+
expected = df.iloc[:, :0]
|
211 |
+
tm.assert_frame_equal(result, expected)
|
212 |
+
|
213 |
+
result = df.iloc[:, 10:11] # 0 < len < start < stop
|
214 |
+
expected = df.iloc[:, :0]
|
215 |
+
tm.assert_frame_equal(result, expected)
|
216 |
+
|
217 |
+
# slice bounds exceeding is ok
|
218 |
+
result = s.iloc[18:30]
|
219 |
+
expected = s.iloc[18:]
|
220 |
+
tm.assert_series_equal(result, expected)
|
221 |
+
|
222 |
+
result = s.iloc[30:]
|
223 |
+
expected = s.iloc[:0]
|
224 |
+
tm.assert_series_equal(result, expected)
|
225 |
+
|
226 |
+
result = s.iloc[30::-1]
|
227 |
+
expected = s.iloc[::-1]
|
228 |
+
tm.assert_series_equal(result, expected)
|
229 |
+
|
230 |
+
# doc example
|
231 |
+
dfl = DataFrame(
|
232 |
+
np.random.default_rng(2).standard_normal((5, 2)), columns=list("AB")
|
233 |
+
)
|
234 |
+
tm.assert_frame_equal(
|
235 |
+
dfl.iloc[:, 2:3],
|
236 |
+
DataFrame(index=dfl.index, columns=Index([], dtype=dfl.columns.dtype)),
|
237 |
+
)
|
238 |
+
tm.assert_frame_equal(dfl.iloc[:, 1:3], dfl.iloc[:, [1]])
|
239 |
+
tm.assert_frame_equal(dfl.iloc[4:6], dfl.iloc[[4]])
|
240 |
+
|
241 |
+
msg = "positional indexers are out-of-bounds"
|
242 |
+
with pytest.raises(IndexError, match=msg):
|
243 |
+
dfl.iloc[[4, 5, 6]]
|
244 |
+
msg = "single positional indexer is out-of-bounds"
|
245 |
+
with pytest.raises(IndexError, match=msg):
|
246 |
+
dfl.iloc[:, 4]
|
247 |
+
|
248 |
+
@pytest.mark.parametrize("index,columns", [(np.arange(20), list("ABCDE"))])
|
249 |
+
@pytest.mark.parametrize(
|
250 |
+
"index_vals,column_vals",
|
251 |
+
[
|
252 |
+
([slice(None), ["A", "D"]]),
|
253 |
+
(["1", "2"], slice(None)),
|
254 |
+
([datetime(2019, 1, 1)], slice(None)),
|
255 |
+
],
|
256 |
+
)
|
257 |
+
def test_iloc_non_integer_raises(self, index, columns, index_vals, column_vals):
|
258 |
+
# GH 25753
|
259 |
+
df = DataFrame(
|
260 |
+
np.random.default_rng(2).standard_normal((len(index), len(columns))),
|
261 |
+
index=index,
|
262 |
+
columns=columns,
|
263 |
+
)
|
264 |
+
msg = ".iloc requires numeric indexers, got"
|
265 |
+
with pytest.raises(IndexError, match=msg):
|
266 |
+
df.iloc[index_vals, column_vals]
|
267 |
+
|
268 |
+
def test_iloc_getitem_invalid_scalar(self, frame_or_series):
|
269 |
+
# GH 21982
|
270 |
+
|
271 |
+
obj = DataFrame(np.arange(100).reshape(10, 10))
|
272 |
+
obj = tm.get_obj(obj, frame_or_series)
|
273 |
+
|
274 |
+
with pytest.raises(TypeError, match="Cannot index by location index"):
|
275 |
+
obj.iloc["a"]
|
276 |
+
|
277 |
+
def test_iloc_array_not_mutating_negative_indices(self):
|
278 |
+
# GH 21867
|
279 |
+
array_with_neg_numbers = np.array([1, 2, -1])
|
280 |
+
array_copy = array_with_neg_numbers.copy()
|
281 |
+
df = DataFrame(
|
282 |
+
{"A": [100, 101, 102], "B": [103, 104, 105], "C": [106, 107, 108]},
|
283 |
+
index=[1, 2, 3],
|
284 |
+
)
|
285 |
+
df.iloc[array_with_neg_numbers]
|
286 |
+
tm.assert_numpy_array_equal(array_with_neg_numbers, array_copy)
|
287 |
+
df.iloc[:, array_with_neg_numbers]
|
288 |
+
tm.assert_numpy_array_equal(array_with_neg_numbers, array_copy)
|
289 |
+
|
290 |
+
def test_iloc_getitem_neg_int_can_reach_first_index(self):
|
291 |
+
# GH10547 and GH10779
|
292 |
+
# negative integers should be able to reach index 0
|
293 |
+
df = DataFrame({"A": [2, 3, 5], "B": [7, 11, 13]})
|
294 |
+
s = df["A"]
|
295 |
+
|
296 |
+
expected = df.iloc[0]
|
297 |
+
result = df.iloc[-3]
|
298 |
+
tm.assert_series_equal(result, expected)
|
299 |
+
|
300 |
+
expected = df.iloc[[0]]
|
301 |
+
result = df.iloc[[-3]]
|
302 |
+
tm.assert_frame_equal(result, expected)
|
303 |
+
|
304 |
+
expected = s.iloc[0]
|
305 |
+
result = s.iloc[-3]
|
306 |
+
assert result == expected
|
307 |
+
|
308 |
+
expected = s.iloc[[0]]
|
309 |
+
result = s.iloc[[-3]]
|
310 |
+
tm.assert_series_equal(result, expected)
|
311 |
+
|
312 |
+
# check the length 1 Series case highlighted in GH10547
|
313 |
+
expected = Series(["a"], index=["A"])
|
314 |
+
result = expected.iloc[[-1]]
|
315 |
+
tm.assert_series_equal(result, expected)
|
316 |
+
|
317 |
+
def test_iloc_getitem_dups(self):
|
318 |
+
# GH 6766
|
319 |
+
df1 = DataFrame([{"A": None, "B": 1}, {"A": 2, "B": 2}])
|
320 |
+
df2 = DataFrame([{"A": 3, "B": 3}, {"A": 4, "B": 4}])
|
321 |
+
df = concat([df1, df2], axis=1)
|
322 |
+
|
323 |
+
# cross-sectional indexing
|
324 |
+
result = df.iloc[0, 0]
|
325 |
+
assert isna(result)
|
326 |
+
|
327 |
+
result = df.iloc[0, :]
|
328 |
+
expected = Series([np.nan, 1, 3, 3], index=["A", "B", "A", "B"], name=0)
|
329 |
+
tm.assert_series_equal(result, expected)
|
330 |
+
|
331 |
+
def test_iloc_getitem_array(self):
|
332 |
+
df = DataFrame(
|
333 |
+
[
|
334 |
+
{"A": 1, "B": 2, "C": 3},
|
335 |
+
{"A": 100, "B": 200, "C": 300},
|
336 |
+
{"A": 1000, "B": 2000, "C": 3000},
|
337 |
+
]
|
338 |
+
)
|
339 |
+
|
340 |
+
expected = DataFrame([{"A": 1, "B": 2, "C": 3}])
|
341 |
+
tm.assert_frame_equal(df.iloc[[0]], expected)
|
342 |
+
|
343 |
+
expected = DataFrame([{"A": 1, "B": 2, "C": 3}, {"A": 100, "B": 200, "C": 300}])
|
344 |
+
tm.assert_frame_equal(df.iloc[[0, 1]], expected)
|
345 |
+
|
346 |
+
expected = DataFrame([{"B": 2, "C": 3}, {"B": 2000, "C": 3000}], index=[0, 2])
|
347 |
+
result = df.iloc[[0, 2], [1, 2]]
|
348 |
+
tm.assert_frame_equal(result, expected)
|
349 |
+
|
350 |
+
def test_iloc_getitem_bool(self):
|
351 |
+
df = DataFrame(
|
352 |
+
[
|
353 |
+
{"A": 1, "B": 2, "C": 3},
|
354 |
+
{"A": 100, "B": 200, "C": 300},
|
355 |
+
{"A": 1000, "B": 2000, "C": 3000},
|
356 |
+
]
|
357 |
+
)
|
358 |
+
|
359 |
+
expected = DataFrame([{"A": 1, "B": 2, "C": 3}, {"A": 100, "B": 200, "C": 300}])
|
360 |
+
result = df.iloc[[True, True, False]]
|
361 |
+
tm.assert_frame_equal(result, expected)
|
362 |
+
|
363 |
+
expected = DataFrame(
|
364 |
+
[{"A": 1, "B": 2, "C": 3}, {"A": 1000, "B": 2000, "C": 3000}], index=[0, 2]
|
365 |
+
)
|
366 |
+
result = df.iloc[lambda x: x.index % 2 == 0]
|
367 |
+
tm.assert_frame_equal(result, expected)
|
368 |
+
|
369 |
+
@pytest.mark.parametrize("index", [[True, False], [True, False, True, False]])
|
370 |
+
def test_iloc_getitem_bool_diff_len(self, index):
|
371 |
+
# GH26658
|
372 |
+
s = Series([1, 2, 3])
|
373 |
+
msg = f"Boolean index has wrong length: {len(index)} instead of {len(s)}"
|
374 |
+
with pytest.raises(IndexError, match=msg):
|
375 |
+
s.iloc[index]
|
376 |
+
|
377 |
+
def test_iloc_getitem_slice(self):
|
378 |
+
df = DataFrame(
|
379 |
+
[
|
380 |
+
{"A": 1, "B": 2, "C": 3},
|
381 |
+
{"A": 100, "B": 200, "C": 300},
|
382 |
+
{"A": 1000, "B": 2000, "C": 3000},
|
383 |
+
]
|
384 |
+
)
|
385 |
+
|
386 |
+
expected = DataFrame([{"A": 1, "B": 2, "C": 3}, {"A": 100, "B": 200, "C": 300}])
|
387 |
+
result = df.iloc[:2]
|
388 |
+
tm.assert_frame_equal(result, expected)
|
389 |
+
|
390 |
+
expected = DataFrame([{"A": 100, "B": 200}], index=[1])
|
391 |
+
result = df.iloc[1:2, 0:2]
|
392 |
+
tm.assert_frame_equal(result, expected)
|
393 |
+
|
394 |
+
expected = DataFrame(
|
395 |
+
[{"A": 1, "C": 3}, {"A": 100, "C": 300}, {"A": 1000, "C": 3000}]
|
396 |
+
)
|
397 |
+
result = df.iloc[:, lambda df: [0, 2]]
|
398 |
+
tm.assert_frame_equal(result, expected)
|
399 |
+
|
400 |
+
def test_iloc_getitem_slice_dups(self):
|
401 |
+
df1 = DataFrame(
|
402 |
+
np.random.default_rng(2).standard_normal((10, 4)),
|
403 |
+
columns=["A", "A", "B", "B"],
|
404 |
+
)
|
405 |
+
df2 = DataFrame(
|
406 |
+
np.random.default_rng(2).integers(0, 10, size=20).reshape(10, 2),
|
407 |
+
columns=["A", "C"],
|
408 |
+
)
|
409 |
+
|
410 |
+
# axis=1
|
411 |
+
df = concat([df1, df2], axis=1)
|
412 |
+
tm.assert_frame_equal(df.iloc[:, :4], df1)
|
413 |
+
tm.assert_frame_equal(df.iloc[:, 4:], df2)
|
414 |
+
|
415 |
+
df = concat([df2, df1], axis=1)
|
416 |
+
tm.assert_frame_equal(df.iloc[:, :2], df2)
|
417 |
+
tm.assert_frame_equal(df.iloc[:, 2:], df1)
|
418 |
+
|
419 |
+
exp = concat([df2, df1.iloc[:, [0]]], axis=1)
|
420 |
+
tm.assert_frame_equal(df.iloc[:, 0:3], exp)
|
421 |
+
|
422 |
+
# axis=0
|
423 |
+
df = concat([df, df], axis=0)
|
424 |
+
tm.assert_frame_equal(df.iloc[0:10, :2], df2)
|
425 |
+
tm.assert_frame_equal(df.iloc[0:10, 2:], df1)
|
426 |
+
tm.assert_frame_equal(df.iloc[10:, :2], df2)
|
427 |
+
tm.assert_frame_equal(df.iloc[10:, 2:], df1)
|
428 |
+
|
429 |
+
def test_iloc_setitem(self, warn_copy_on_write):
|
430 |
+
df = DataFrame(
|
431 |
+
np.random.default_rng(2).standard_normal((4, 4)),
|
432 |
+
index=np.arange(0, 8, 2),
|
433 |
+
columns=np.arange(0, 12, 3),
|
434 |
+
)
|
435 |
+
|
436 |
+
df.iloc[1, 1] = 1
|
437 |
+
result = df.iloc[1, 1]
|
438 |
+
assert result == 1
|
439 |
+
|
440 |
+
df.iloc[:, 2:3] = 0
|
441 |
+
expected = df.iloc[:, 2:3]
|
442 |
+
result = df.iloc[:, 2:3]
|
443 |
+
tm.assert_frame_equal(result, expected)
|
444 |
+
|
445 |
+
# GH5771
|
446 |
+
s = Series(0, index=[4, 5, 6])
|
447 |
+
s.iloc[1:2] += 1
|
448 |
+
expected = Series([0, 1, 0], index=[4, 5, 6])
|
449 |
+
tm.assert_series_equal(s, expected)
|
450 |
+
|
451 |
+
def test_iloc_setitem_axis_argument(self):
|
452 |
+
# GH45032
|
453 |
+
df = DataFrame([[6, "c", 10], [7, "d", 11], [8, "e", 12]])
|
454 |
+
df[1] = df[1].astype(object)
|
455 |
+
expected = DataFrame([[6, "c", 10], [7, "d", 11], [5, 5, 5]])
|
456 |
+
expected[1] = expected[1].astype(object)
|
457 |
+
df.iloc(axis=0)[2] = 5
|
458 |
+
tm.assert_frame_equal(df, expected)
|
459 |
+
|
460 |
+
df = DataFrame([[6, "c", 10], [7, "d", 11], [8, "e", 12]])
|
461 |
+
df[1] = df[1].astype(object)
|
462 |
+
expected = DataFrame([[6, "c", 5], [7, "d", 5], [8, "e", 5]])
|
463 |
+
expected[1] = expected[1].astype(object)
|
464 |
+
df.iloc(axis=1)[2] = 5
|
465 |
+
tm.assert_frame_equal(df, expected)
|
466 |
+
|
467 |
+
def test_iloc_setitem_list(self):
|
468 |
+
# setitem with an iloc list
|
469 |
+
df = DataFrame(
|
470 |
+
np.arange(9).reshape((3, 3)), index=["A", "B", "C"], columns=["A", "B", "C"]
|
471 |
+
)
|
472 |
+
df.iloc[[0, 1], [1, 2]]
|
473 |
+
df.iloc[[0, 1], [1, 2]] += 100
|
474 |
+
|
475 |
+
expected = DataFrame(
|
476 |
+
np.array([0, 101, 102, 3, 104, 105, 6, 7, 8]).reshape((3, 3)),
|
477 |
+
index=["A", "B", "C"],
|
478 |
+
columns=["A", "B", "C"],
|
479 |
+
)
|
480 |
+
tm.assert_frame_equal(df, expected)
|
481 |
+
|
482 |
+
def test_iloc_setitem_pandas_object(self):
|
483 |
+
# GH 17193
|
484 |
+
s_orig = Series([0, 1, 2, 3])
|
485 |
+
expected = Series([0, -1, -2, 3])
|
486 |
+
|
487 |
+
s = s_orig.copy()
|
488 |
+
s.iloc[Series([1, 2])] = [-1, -2]
|
489 |
+
tm.assert_series_equal(s, expected)
|
490 |
+
|
491 |
+
s = s_orig.copy()
|
492 |
+
s.iloc[Index([1, 2])] = [-1, -2]
|
493 |
+
tm.assert_series_equal(s, expected)
|
494 |
+
|
495 |
+
def test_iloc_setitem_dups(self):
|
496 |
+
# GH 6766
|
497 |
+
# iloc with a mask aligning from another iloc
|
498 |
+
df1 = DataFrame([{"A": None, "B": 1}, {"A": 2, "B": 2}])
|
499 |
+
df2 = DataFrame([{"A": 3, "B": 3}, {"A": 4, "B": 4}])
|
500 |
+
df = concat([df1, df2], axis=1)
|
501 |
+
|
502 |
+
expected = df.fillna(3)
|
503 |
+
inds = np.isnan(df.iloc[:, 0])
|
504 |
+
mask = inds[inds].index
|
505 |
+
df.iloc[mask, 0] = df.iloc[mask, 2]
|
506 |
+
tm.assert_frame_equal(df, expected)
|
507 |
+
|
508 |
+
# del a dup column across blocks
|
509 |
+
expected = DataFrame({0: [1, 2], 1: [3, 4]})
|
510 |
+
expected.columns = ["B", "B"]
|
511 |
+
del df["A"]
|
512 |
+
tm.assert_frame_equal(df, expected)
|
513 |
+
|
514 |
+
# assign back to self
|
515 |
+
df.iloc[[0, 1], [0, 1]] = df.iloc[[0, 1], [0, 1]]
|
516 |
+
tm.assert_frame_equal(df, expected)
|
517 |
+
|
518 |
+
# reversed x 2
|
519 |
+
df.iloc[[1, 0], [0, 1]] = df.iloc[[1, 0], [0, 1]].reset_index(drop=True)
|
520 |
+
df.iloc[[1, 0], [0, 1]] = df.iloc[[1, 0], [0, 1]].reset_index(drop=True)
|
521 |
+
tm.assert_frame_equal(df, expected)
|
522 |
+
|
523 |
+
def test_iloc_setitem_frame_duplicate_columns_multiple_blocks(
|
524 |
+
self, using_array_manager
|
525 |
+
):
|
526 |
+
# Same as the "assign back to self" check in test_iloc_setitem_dups
|
527 |
+
# but on a DataFrame with multiple blocks
|
528 |
+
df = DataFrame([[0, 1], [2, 3]], columns=["B", "B"])
|
529 |
+
|
530 |
+
# setting float values that can be held by existing integer arrays
|
531 |
+
# is inplace
|
532 |
+
df.iloc[:, 0] = df.iloc[:, 0].astype("f8")
|
533 |
+
if not using_array_manager:
|
534 |
+
assert len(df._mgr.blocks) == 1
|
535 |
+
|
536 |
+
# if the assigned values cannot be held by existing integer arrays,
|
537 |
+
# we cast
|
538 |
+
with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):
|
539 |
+
df.iloc[:, 0] = df.iloc[:, 0] + 0.5
|
540 |
+
if not using_array_manager:
|
541 |
+
assert len(df._mgr.blocks) == 2
|
542 |
+
|
543 |
+
expected = df.copy()
|
544 |
+
|
545 |
+
# assign back to self
|
546 |
+
df.iloc[[0, 1], [0, 1]] = df.iloc[[0, 1], [0, 1]]
|
547 |
+
|
548 |
+
tm.assert_frame_equal(df, expected)
|
549 |
+
|
550 |
+
# TODO: GH#27620 this test used to compare iloc against ix; check if this
|
551 |
+
# is redundant with another test comparing iloc against loc
|
552 |
+
def test_iloc_getitem_frame(self):
|
553 |
+
df = DataFrame(
|
554 |
+
np.random.default_rng(2).standard_normal((10, 4)),
|
555 |
+
index=range(0, 20, 2),
|
556 |
+
columns=range(0, 8, 2),
|
557 |
+
)
|
558 |
+
|
559 |
+
result = df.iloc[2]
|
560 |
+
exp = df.loc[4]
|
561 |
+
tm.assert_series_equal(result, exp)
|
562 |
+
|
563 |
+
result = df.iloc[2, 2]
|
564 |
+
exp = df.loc[4, 4]
|
565 |
+
assert result == exp
|
566 |
+
|
567 |
+
# slice
|
568 |
+
result = df.iloc[4:8]
|
569 |
+
expected = df.loc[8:14]
|
570 |
+
tm.assert_frame_equal(result, expected)
|
571 |
+
|
572 |
+
result = df.iloc[:, 2:3]
|
573 |
+
expected = df.loc[:, 4:5]
|
574 |
+
tm.assert_frame_equal(result, expected)
|
575 |
+
|
576 |
+
# list of integers
|
577 |
+
result = df.iloc[[0, 1, 3]]
|
578 |
+
expected = df.loc[[0, 2, 6]]
|
579 |
+
tm.assert_frame_equal(result, expected)
|
580 |
+
|
581 |
+
result = df.iloc[[0, 1, 3], [0, 1]]
|
582 |
+
expected = df.loc[[0, 2, 6], [0, 2]]
|
583 |
+
tm.assert_frame_equal(result, expected)
|
584 |
+
|
585 |
+
# neg indices
|
586 |
+
result = df.iloc[[-1, 1, 3], [-1, 1]]
|
587 |
+
expected = df.loc[[18, 2, 6], [6, 2]]
|
588 |
+
tm.assert_frame_equal(result, expected)
|
589 |
+
|
590 |
+
# dups indices
|
591 |
+
result = df.iloc[[-1, -1, 1, 3], [-1, 1]]
|
592 |
+
expected = df.loc[[18, 18, 2, 6], [6, 2]]
|
593 |
+
tm.assert_frame_equal(result, expected)
|
594 |
+
|
595 |
+
# with index-like
|
596 |
+
s = Series(index=range(1, 5), dtype=object)
|
597 |
+
result = df.iloc[s.index]
|
598 |
+
expected = df.loc[[2, 4, 6, 8]]
|
599 |
+
tm.assert_frame_equal(result, expected)
|
600 |
+
|
601 |
+
def test_iloc_getitem_labelled_frame(self):
|
602 |
+
# try with labelled frame
|
603 |
+
df = DataFrame(
|
604 |
+
np.random.default_rng(2).standard_normal((10, 4)),
|
605 |
+
index=list("abcdefghij"),
|
606 |
+
columns=list("ABCD"),
|
607 |
+
)
|
608 |
+
|
609 |
+
result = df.iloc[1, 1]
|
610 |
+
exp = df.loc["b", "B"]
|
611 |
+
assert result == exp
|
612 |
+
|
613 |
+
result = df.iloc[:, 2:3]
|
614 |
+
expected = df.loc[:, ["C"]]
|
615 |
+
tm.assert_frame_equal(result, expected)
|
616 |
+
|
617 |
+
# negative indexing
|
618 |
+
result = df.iloc[-1, -1]
|
619 |
+
exp = df.loc["j", "D"]
|
620 |
+
assert result == exp
|
621 |
+
|
622 |
+
# out-of-bounds exception
|
623 |
+
msg = "index 5 is out of bounds for axis 0 with size 4|index out of bounds"
|
624 |
+
with pytest.raises(IndexError, match=msg):
|
625 |
+
df.iloc[10, 5]
|
626 |
+
|
627 |
+
# trying to use a label
|
628 |
+
msg = (
|
629 |
+
r"Location based indexing can only have \[integer, integer "
|
630 |
+
r"slice \(START point is INCLUDED, END point is EXCLUDED\), "
|
631 |
+
r"listlike of integers, boolean array\] types"
|
632 |
+
)
|
633 |
+
with pytest.raises(ValueError, match=msg):
|
634 |
+
df.iloc["j", "D"]
|
635 |
+
|
636 |
+
def test_iloc_getitem_doc_issue(self, using_array_manager):
|
637 |
+
# multi axis slicing issue with single block
|
638 |
+
# surfaced in GH 6059
|
639 |
+
|
640 |
+
arr = np.random.default_rng(2).standard_normal((6, 4))
|
641 |
+
index = date_range("20130101", periods=6)
|
642 |
+
columns = list("ABCD")
|
643 |
+
df = DataFrame(arr, index=index, columns=columns)
|
644 |
+
|
645 |
+
# defines ref_locs
|
646 |
+
df.describe()
|
647 |
+
|
648 |
+
result = df.iloc[3:5, 0:2]
|
649 |
+
|
650 |
+
expected = DataFrame(arr[3:5, 0:2], index=index[3:5], columns=columns[0:2])
|
651 |
+
tm.assert_frame_equal(result, expected)
|
652 |
+
|
653 |
+
# for dups
|
654 |
+
df.columns = list("aaaa")
|
655 |
+
result = df.iloc[3:5, 0:2]
|
656 |
+
|
657 |
+
expected = DataFrame(arr[3:5, 0:2], index=index[3:5], columns=list("aa"))
|
658 |
+
tm.assert_frame_equal(result, expected)
|
659 |
+
|
660 |
+
# related
|
661 |
+
arr = np.random.default_rng(2).standard_normal((6, 4))
|
662 |
+
index = list(range(0, 12, 2))
|
663 |
+
columns = list(range(0, 8, 2))
|
664 |
+
df = DataFrame(arr, index=index, columns=columns)
|
665 |
+
|
666 |
+
if not using_array_manager:
|
667 |
+
df._mgr.blocks[0].mgr_locs
|
668 |
+
result = df.iloc[1:5, 2:4]
|
669 |
+
expected = DataFrame(arr[1:5, 2:4], index=index[1:5], columns=columns[2:4])
|
670 |
+
tm.assert_frame_equal(result, expected)
|
671 |
+
|
672 |
+
def test_iloc_setitem_series(self):
|
673 |
+
df = DataFrame(
|
674 |
+
np.random.default_rng(2).standard_normal((10, 4)),
|
675 |
+
index=list("abcdefghij"),
|
676 |
+
columns=list("ABCD"),
|
677 |
+
)
|
678 |
+
|
679 |
+
df.iloc[1, 1] = 1
|
680 |
+
result = df.iloc[1, 1]
|
681 |
+
assert result == 1
|
682 |
+
|
683 |
+
df.iloc[:, 2:3] = 0
|
684 |
+
expected = df.iloc[:, 2:3]
|
685 |
+
result = df.iloc[:, 2:3]
|
686 |
+
tm.assert_frame_equal(result, expected)
|
687 |
+
|
688 |
+
s = Series(np.random.default_rng(2).standard_normal(10), index=range(0, 20, 2))
|
689 |
+
|
690 |
+
s.iloc[1] = 1
|
691 |
+
result = s.iloc[1]
|
692 |
+
assert result == 1
|
693 |
+
|
694 |
+
s.iloc[:4] = 0
|
695 |
+
expected = s.iloc[:4]
|
696 |
+
result = s.iloc[:4]
|
697 |
+
tm.assert_series_equal(result, expected)
|
698 |
+
|
699 |
+
s = Series([-1] * 6)
|
700 |
+
s.iloc[0::2] = [0, 2, 4]
|
701 |
+
s.iloc[1::2] = [1, 3, 5]
|
702 |
+
result = s
|
703 |
+
expected = Series([0, 1, 2, 3, 4, 5])
|
704 |
+
tm.assert_series_equal(result, expected)
|
705 |
+
|
706 |
+
def test_iloc_setitem_list_of_lists(self):
|
707 |
+
# GH 7551
|
708 |
+
# list-of-list is set incorrectly in mixed vs. single dtyped frames
|
709 |
+
df = DataFrame(
|
710 |
+
{"A": np.arange(5, dtype="int64"), "B": np.arange(5, 10, dtype="int64")}
|
711 |
+
)
|
712 |
+
df.iloc[2:4] = [[10, 11], [12, 13]]
|
713 |
+
expected = DataFrame({"A": [0, 1, 10, 12, 4], "B": [5, 6, 11, 13, 9]})
|
714 |
+
tm.assert_frame_equal(df, expected)
|
715 |
+
|
716 |
+
df = DataFrame(
|
717 |
+
{"A": ["a", "b", "c", "d", "e"], "B": np.arange(5, 10, dtype="int64")}
|
718 |
+
)
|
719 |
+
df.iloc[2:4] = [["x", 11], ["y", 13]]
|
720 |
+
expected = DataFrame({"A": ["a", "b", "x", "y", "e"], "B": [5, 6, 11, 13, 9]})
|
721 |
+
tm.assert_frame_equal(df, expected)
|
722 |
+
|
723 |
+
@pytest.mark.parametrize("indexer", [[0], slice(None, 1, None), np.array([0])])
|
724 |
+
@pytest.mark.parametrize("value", [["Z"], np.array(["Z"])])
|
725 |
+
def test_iloc_setitem_with_scalar_index(self, indexer, value):
|
726 |
+
# GH #19474
|
727 |
+
# assigning like "df.iloc[0, [0]] = ['Z']" should be evaluated
|
728 |
+
# elementwisely, not using "setter('A', ['Z'])".
|
729 |
+
|
730 |
+
# Set object type to avoid upcast when setting "Z"
|
731 |
+
df = DataFrame([[1, 2], [3, 4]], columns=["A", "B"]).astype({"A": object})
|
732 |
+
df.iloc[0, indexer] = value
|
733 |
+
result = df.iloc[0, 0]
|
734 |
+
|
735 |
+
assert is_scalar(result) and result == "Z"
|
736 |
+
|
737 |
+
@pytest.mark.filterwarnings("ignore::UserWarning")
|
738 |
+
def test_iloc_mask(self):
|
739 |
+
# GH 3631, iloc with a mask (of a series) should raise
|
740 |
+
df = DataFrame(list(range(5)), index=list("ABCDE"), columns=["a"])
|
741 |
+
mask = df.a % 2 == 0
|
742 |
+
msg = "iLocation based boolean indexing cannot use an indexable as a mask"
|
743 |
+
with pytest.raises(ValueError, match=msg):
|
744 |
+
df.iloc[mask]
|
745 |
+
mask.index = range(len(mask))
|
746 |
+
msg = "iLocation based boolean indexing on an integer type is not available"
|
747 |
+
with pytest.raises(NotImplementedError, match=msg):
|
748 |
+
df.iloc[mask]
|
749 |
+
|
750 |
+
# ndarray ok
|
751 |
+
result = df.iloc[np.array([True] * len(mask), dtype=bool)]
|
752 |
+
tm.assert_frame_equal(result, df)
|
753 |
+
|
754 |
+
# the possibilities
|
755 |
+
locs = np.arange(4)
|
756 |
+
nums = 2**locs
|
757 |
+
reps = [bin(num) for num in nums]
|
758 |
+
df = DataFrame({"locs": locs, "nums": nums}, reps)
|
759 |
+
|
760 |
+
expected = {
|
761 |
+
(None, ""): "0b1100",
|
762 |
+
(None, ".loc"): "0b1100",
|
763 |
+
(None, ".iloc"): "0b1100",
|
764 |
+
("index", ""): "0b11",
|
765 |
+
("index", ".loc"): "0b11",
|
766 |
+
("index", ".iloc"): (
|
767 |
+
"iLocation based boolean indexing cannot use an indexable as a mask"
|
768 |
+
),
|
769 |
+
("locs", ""): "Unalignable boolean Series provided as indexer "
|
770 |
+
"(index of the boolean Series and of the indexed "
|
771 |
+
"object do not match).",
|
772 |
+
("locs", ".loc"): "Unalignable boolean Series provided as indexer "
|
773 |
+
"(index of the boolean Series and of the "
|
774 |
+
"indexed object do not match).",
|
775 |
+
("locs", ".iloc"): (
|
776 |
+
"iLocation based boolean indexing on an "
|
777 |
+
"integer type is not available"
|
778 |
+
),
|
779 |
+
}
|
780 |
+
|
781 |
+
# UserWarnings from reindex of a boolean mask
|
782 |
+
for idx in [None, "index", "locs"]:
|
783 |
+
mask = (df.nums > 2).values
|
784 |
+
if idx:
|
785 |
+
mask_index = getattr(df, idx)[::-1]
|
786 |
+
mask = Series(mask, list(mask_index))
|
787 |
+
for method in ["", ".loc", ".iloc"]:
|
788 |
+
try:
|
789 |
+
if method:
|
790 |
+
accessor = getattr(df, method[1:])
|
791 |
+
else:
|
792 |
+
accessor = df
|
793 |
+
answer = str(bin(accessor[mask]["nums"].sum()))
|
794 |
+
except (ValueError, IndexingError, NotImplementedError) as err:
|
795 |
+
answer = str(err)
|
796 |
+
|
797 |
+
key = (
|
798 |
+
idx,
|
799 |
+
method,
|
800 |
+
)
|
801 |
+
r = expected.get(key)
|
802 |
+
if r != answer:
|
803 |
+
raise AssertionError(
|
804 |
+
f"[{key}] does not match [{answer}], received [{r}]"
|
805 |
+
)
|
806 |
+
|
807 |
+
def test_iloc_non_unique_indexing(self):
|
808 |
+
# GH 4017, non-unique indexing (on the axis)
|
809 |
+
df = DataFrame({"A": [0.1] * 3000, "B": [1] * 3000})
|
810 |
+
idx = np.arange(30) * 99
|
811 |
+
expected = df.iloc[idx]
|
812 |
+
|
813 |
+
df3 = concat([df, 2 * df, 3 * df])
|
814 |
+
result = df3.iloc[idx]
|
815 |
+
|
816 |
+
tm.assert_frame_equal(result, expected)
|
817 |
+
|
818 |
+
df2 = DataFrame({"A": [0.1] * 1000, "B": [1] * 1000})
|
819 |
+
df2 = concat([df2, 2 * df2, 3 * df2])
|
820 |
+
|
821 |
+
with pytest.raises(KeyError, match="not in index"):
|
822 |
+
df2.loc[idx]
|
823 |
+
|
824 |
+
def test_iloc_empty_list_indexer_is_ok(self):
|
825 |
+
df = DataFrame(
|
826 |
+
np.ones((5, 2)),
|
827 |
+
index=Index([f"i-{i}" for i in range(5)], name="a"),
|
828 |
+
columns=Index([f"i-{i}" for i in range(2)], name="a"),
|
829 |
+
)
|
830 |
+
# vertical empty
|
831 |
+
tm.assert_frame_equal(
|
832 |
+
df.iloc[:, []],
|
833 |
+
df.iloc[:, :0],
|
834 |
+
check_index_type=True,
|
835 |
+
check_column_type=True,
|
836 |
+
)
|
837 |
+
# horizontal empty
|
838 |
+
tm.assert_frame_equal(
|
839 |
+
df.iloc[[], :],
|
840 |
+
df.iloc[:0, :],
|
841 |
+
check_index_type=True,
|
842 |
+
check_column_type=True,
|
843 |
+
)
|
844 |
+
# horizontal empty
|
845 |
+
tm.assert_frame_equal(
|
846 |
+
df.iloc[[]], df.iloc[:0, :], check_index_type=True, check_column_type=True
|
847 |
+
)
|
848 |
+
|
849 |
+
def test_identity_slice_returns_new_object(
|
850 |
+
self, using_copy_on_write, warn_copy_on_write
|
851 |
+
):
|
852 |
+
# GH13873
|
853 |
+
original_df = DataFrame({"a": [1, 2, 3]})
|
854 |
+
sliced_df = original_df.iloc[:]
|
855 |
+
assert sliced_df is not original_df
|
856 |
+
|
857 |
+
# should be a shallow copy
|
858 |
+
assert np.shares_memory(original_df["a"], sliced_df["a"])
|
859 |
+
|
860 |
+
# Setting using .loc[:, "a"] sets inplace so alters both sliced and orig
|
861 |
+
# depending on CoW
|
862 |
+
with tm.assert_cow_warning(warn_copy_on_write):
|
863 |
+
original_df.loc[:, "a"] = [4, 4, 4]
|
864 |
+
if using_copy_on_write:
|
865 |
+
assert (sliced_df["a"] == [1, 2, 3]).all()
|
866 |
+
else:
|
867 |
+
assert (sliced_df["a"] == 4).all()
|
868 |
+
|
869 |
+
original_series = Series([1, 2, 3, 4, 5, 6])
|
870 |
+
sliced_series = original_series.iloc[:]
|
871 |
+
assert sliced_series is not original_series
|
872 |
+
|
873 |
+
# should also be a shallow copy
|
874 |
+
with tm.assert_cow_warning(warn_copy_on_write):
|
875 |
+
original_series[:3] = [7, 8, 9]
|
876 |
+
if using_copy_on_write:
|
877 |
+
# shallow copy not updated (CoW)
|
878 |
+
assert all(sliced_series[:3] == [1, 2, 3])
|
879 |
+
else:
|
880 |
+
assert all(sliced_series[:3] == [7, 8, 9])
|
881 |
+
|
882 |
+
def test_indexing_zerodim_np_array(self):
|
883 |
+
# GH24919
|
884 |
+
df = DataFrame([[1, 2], [3, 4]])
|
885 |
+
result = df.iloc[np.array(0)]
|
886 |
+
s = Series([1, 2], name=0)
|
887 |
+
tm.assert_series_equal(result, s)
|
888 |
+
|
889 |
+
def test_series_indexing_zerodim_np_array(self):
|
890 |
+
# GH24919
|
891 |
+
s = Series([1, 2])
|
892 |
+
result = s.iloc[np.array(0)]
|
893 |
+
assert result == 1
|
894 |
+
|
895 |
+
def test_iloc_setitem_categorical_updates_inplace(self):
|
896 |
+
# Mixed dtype ensures we go through take_split_path in setitem_with_indexer
|
897 |
+
cat = Categorical(["A", "B", "C"])
|
898 |
+
df = DataFrame({1: cat, 2: [1, 2, 3]}, copy=False)
|
899 |
+
|
900 |
+
assert tm.shares_memory(df[1], cat)
|
901 |
+
|
902 |
+
# With the enforcement of GH#45333 in 2.0, this modifies original
|
903 |
+
# values inplace
|
904 |
+
df.iloc[:, 0] = cat[::-1]
|
905 |
+
|
906 |
+
assert tm.shares_memory(df[1], cat)
|
907 |
+
expected = Categorical(["C", "B", "A"], categories=["A", "B", "C"])
|
908 |
+
tm.assert_categorical_equal(cat, expected)
|
909 |
+
|
910 |
+
def test_iloc_with_boolean_operation(self):
|
911 |
+
# GH 20627
|
912 |
+
result = DataFrame([[0, 1], [2, 3], [4, 5], [6, np.nan]])
|
913 |
+
result.iloc[result.index <= 2] *= 2
|
914 |
+
expected = DataFrame([[0, 2], [4, 6], [8, 10], [6, np.nan]])
|
915 |
+
tm.assert_frame_equal(result, expected)
|
916 |
+
|
917 |
+
result.iloc[result.index > 2] *= 2
|
918 |
+
expected = DataFrame([[0, 2], [4, 6], [8, 10], [12, np.nan]])
|
919 |
+
tm.assert_frame_equal(result, expected)
|
920 |
+
|
921 |
+
result.iloc[[True, True, False, False]] *= 2
|
922 |
+
expected = DataFrame([[0, 4], [8, 12], [8, 10], [12, np.nan]])
|
923 |
+
tm.assert_frame_equal(result, expected)
|
924 |
+
|
925 |
+
result.iloc[[False, False, True, True]] /= 2
|
926 |
+
expected = DataFrame([[0, 4.0], [8, 12.0], [4, 5.0], [6, np.nan]])
|
927 |
+
tm.assert_frame_equal(result, expected)
|
928 |
+
|
929 |
+
def test_iloc_getitem_singlerow_slice_categoricaldtype_gives_series(self):
|
930 |
+
# GH#29521
|
931 |
+
df = DataFrame({"x": Categorical("a b c d e".split())})
|
932 |
+
result = df.iloc[0]
|
933 |
+
raw_cat = Categorical(["a"], categories=["a", "b", "c", "d", "e"])
|
934 |
+
expected = Series(raw_cat, index=["x"], name=0, dtype="category")
|
935 |
+
|
936 |
+
tm.assert_series_equal(result, expected)
|
937 |
+
|
938 |
+
def test_iloc_getitem_categorical_values(self):
|
939 |
+
# GH#14580
|
940 |
+
# test iloc() on Series with Categorical data
|
941 |
+
|
942 |
+
ser = Series([1, 2, 3]).astype("category")
|
943 |
+
|
944 |
+
# get slice
|
945 |
+
result = ser.iloc[0:2]
|
946 |
+
expected = Series([1, 2]).astype(CategoricalDtype([1, 2, 3]))
|
947 |
+
tm.assert_series_equal(result, expected)
|
948 |
+
|
949 |
+
# get list of indexes
|
950 |
+
result = ser.iloc[[0, 1]]
|
951 |
+
expected = Series([1, 2]).astype(CategoricalDtype([1, 2, 3]))
|
952 |
+
tm.assert_series_equal(result, expected)
|
953 |
+
|
954 |
+
# get boolean array
|
955 |
+
result = ser.iloc[[True, False, False]]
|
956 |
+
expected = Series([1]).astype(CategoricalDtype([1, 2, 3]))
|
957 |
+
tm.assert_series_equal(result, expected)
|
958 |
+
|
959 |
+
@pytest.mark.parametrize("value", [None, NaT, np.nan])
|
960 |
+
def test_iloc_setitem_td64_values_cast_na(self, value):
|
961 |
+
# GH#18586
|
962 |
+
series = Series([0, 1, 2], dtype="timedelta64[ns]")
|
963 |
+
series.iloc[0] = value
|
964 |
+
expected = Series([NaT, 1, 2], dtype="timedelta64[ns]")
|
965 |
+
tm.assert_series_equal(series, expected)
|
966 |
+
|
967 |
+
@pytest.mark.parametrize("not_na", [Interval(0, 1), "a", 1.0])
|
968 |
+
def test_setitem_mix_of_nan_and_interval(self, not_na, nulls_fixture):
|
969 |
+
# GH#27937
|
970 |
+
dtype = CategoricalDtype(categories=[not_na])
|
971 |
+
ser = Series(
|
972 |
+
[nulls_fixture, nulls_fixture, nulls_fixture, nulls_fixture], dtype=dtype
|
973 |
+
)
|
974 |
+
ser.iloc[:3] = [nulls_fixture, not_na, nulls_fixture]
|
975 |
+
exp = Series([nulls_fixture, not_na, nulls_fixture, nulls_fixture], dtype=dtype)
|
976 |
+
tm.assert_series_equal(ser, exp)
|
977 |
+
|
978 |
+
def test_iloc_setitem_empty_frame_raises_with_3d_ndarray(self):
|
979 |
+
idx = Index([])
|
980 |
+
obj = DataFrame(
|
981 |
+
np.random.default_rng(2).standard_normal((len(idx), len(idx))),
|
982 |
+
index=idx,
|
983 |
+
columns=idx,
|
984 |
+
)
|
985 |
+
nd3 = np.random.default_rng(2).integers(5, size=(2, 2, 2))
|
986 |
+
|
987 |
+
msg = f"Cannot set values with ndim > {obj.ndim}"
|
988 |
+
with pytest.raises(ValueError, match=msg):
|
989 |
+
obj.iloc[nd3] = 0
|
990 |
+
|
991 |
+
@pytest.mark.parametrize("indexer", [tm.loc, tm.iloc])
|
992 |
+
def test_iloc_getitem_read_only_values(self, indexer):
|
993 |
+
# GH#10043 this is fundamentally a test for iloc, but test loc while
|
994 |
+
# we're here
|
995 |
+
rw_array = np.eye(10)
|
996 |
+
rw_df = DataFrame(rw_array)
|
997 |
+
|
998 |
+
ro_array = np.eye(10)
|
999 |
+
ro_array.setflags(write=False)
|
1000 |
+
ro_df = DataFrame(ro_array)
|
1001 |
+
|
1002 |
+
tm.assert_frame_equal(indexer(rw_df)[[1, 2, 3]], indexer(ro_df)[[1, 2, 3]])
|
1003 |
+
tm.assert_frame_equal(indexer(rw_df)[[1]], indexer(ro_df)[[1]])
|
1004 |
+
tm.assert_series_equal(indexer(rw_df)[1], indexer(ro_df)[1])
|
1005 |
+
tm.assert_frame_equal(indexer(rw_df)[1:3], indexer(ro_df)[1:3])
|
1006 |
+
|
1007 |
+
def test_iloc_getitem_readonly_key(self):
|
1008 |
+
# GH#17192 iloc with read-only array raising TypeError
|
1009 |
+
df = DataFrame({"data": np.ones(100, dtype="float64")})
|
1010 |
+
indices = np.array([1, 3, 6])
|
1011 |
+
indices.flags.writeable = False
|
1012 |
+
|
1013 |
+
result = df.iloc[indices]
|
1014 |
+
expected = df.loc[[1, 3, 6]]
|
1015 |
+
tm.assert_frame_equal(result, expected)
|
1016 |
+
|
1017 |
+
result = df["data"].iloc[indices]
|
1018 |
+
expected = df["data"].loc[[1, 3, 6]]
|
1019 |
+
tm.assert_series_equal(result, expected)
|
1020 |
+
|
1021 |
+
def test_iloc_assign_series_to_df_cell(self):
|
1022 |
+
# GH 37593
|
1023 |
+
df = DataFrame(columns=["a"], index=[0])
|
1024 |
+
df.iloc[0, 0] = Series([1, 2, 3])
|
1025 |
+
expected = DataFrame({"a": [Series([1, 2, 3])]}, columns=["a"], index=[0])
|
1026 |
+
tm.assert_frame_equal(df, expected)
|
1027 |
+
|
1028 |
+
@pytest.mark.parametrize("klass", [list, np.array])
|
1029 |
+
def test_iloc_setitem_bool_indexer(self, klass):
|
1030 |
+
# GH#36741
|
1031 |
+
df = DataFrame({"flag": ["x", "y", "z"], "value": [1, 3, 4]})
|
1032 |
+
indexer = klass([True, False, False])
|
1033 |
+
df.iloc[indexer, 1] = df.iloc[indexer, 1] * 2
|
1034 |
+
expected = DataFrame({"flag": ["x", "y", "z"], "value": [2, 3, 4]})
|
1035 |
+
tm.assert_frame_equal(df, expected)
|
1036 |
+
|
1037 |
+
@pytest.mark.parametrize("indexer", [[1], slice(1, 2)])
|
1038 |
+
def test_iloc_setitem_pure_position_based(self, indexer):
|
1039 |
+
# GH#22046
|
1040 |
+
df1 = DataFrame({"a2": [11, 12, 13], "b2": [14, 15, 16]})
|
1041 |
+
df2 = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]})
|
1042 |
+
df2.iloc[:, indexer] = df1.iloc[:, [0]]
|
1043 |
+
expected = DataFrame({"a": [1, 2, 3], "b": [11, 12, 13], "c": [7, 8, 9]})
|
1044 |
+
tm.assert_frame_equal(df2, expected)
|
1045 |
+
|
1046 |
+
def test_iloc_setitem_dictionary_value(self):
|
1047 |
+
# GH#37728
|
1048 |
+
df = DataFrame({"x": [1, 2], "y": [2, 2]})
|
1049 |
+
rhs = {"x": 9, "y": 99}
|
1050 |
+
df.iloc[1] = rhs
|
1051 |
+
expected = DataFrame({"x": [1, 9], "y": [2, 99]})
|
1052 |
+
tm.assert_frame_equal(df, expected)
|
1053 |
+
|
1054 |
+
# GH#38335 same thing, mixed dtypes
|
1055 |
+
df = DataFrame({"x": [1, 2], "y": [2.0, 2.0]})
|
1056 |
+
df.iloc[1] = rhs
|
1057 |
+
expected = DataFrame({"x": [1, 9], "y": [2.0, 99.0]})
|
1058 |
+
tm.assert_frame_equal(df, expected)
|
1059 |
+
|
1060 |
+
def test_iloc_getitem_float_duplicates(self):
|
1061 |
+
df = DataFrame(
|
1062 |
+
np.random.default_rng(2).standard_normal((3, 3)),
|
1063 |
+
index=[0.1, 0.2, 0.2],
|
1064 |
+
columns=list("abc"),
|
1065 |
+
)
|
1066 |
+
expect = df.iloc[1:]
|
1067 |
+
tm.assert_frame_equal(df.loc[0.2], expect)
|
1068 |
+
|
1069 |
+
expect = df.iloc[1:, 0]
|
1070 |
+
tm.assert_series_equal(df.loc[0.2, "a"], expect)
|
1071 |
+
|
1072 |
+
df.index = [1, 0.2, 0.2]
|
1073 |
+
expect = df.iloc[1:]
|
1074 |
+
tm.assert_frame_equal(df.loc[0.2], expect)
|
1075 |
+
|
1076 |
+
expect = df.iloc[1:, 0]
|
1077 |
+
tm.assert_series_equal(df.loc[0.2, "a"], expect)
|
1078 |
+
|
1079 |
+
df = DataFrame(
|
1080 |
+
np.random.default_rng(2).standard_normal((4, 3)),
|
1081 |
+
index=[1, 0.2, 0.2, 1],
|
1082 |
+
columns=list("abc"),
|
1083 |
+
)
|
1084 |
+
expect = df.iloc[1:-1]
|
1085 |
+
tm.assert_frame_equal(df.loc[0.2], expect)
|
1086 |
+
|
1087 |
+
expect = df.iloc[1:-1, 0]
|
1088 |
+
tm.assert_series_equal(df.loc[0.2, "a"], expect)
|
1089 |
+
|
1090 |
+
df.index = [0.1, 0.2, 2, 0.2]
|
1091 |
+
expect = df.iloc[[1, -1]]
|
1092 |
+
tm.assert_frame_equal(df.loc[0.2], expect)
|
1093 |
+
|
1094 |
+
expect = df.iloc[[1, -1], 0]
|
1095 |
+
tm.assert_series_equal(df.loc[0.2, "a"], expect)
|
1096 |
+
|
1097 |
+
def test_iloc_setitem_custom_object(self):
|
1098 |
+
# iloc with an object
|
1099 |
+
class TO:
|
1100 |
+
def __init__(self, value) -> None:
|
1101 |
+
self.value = value
|
1102 |
+
|
1103 |
+
def __str__(self) -> str:
|
1104 |
+
return f"[{self.value}]"
|
1105 |
+
|
1106 |
+
__repr__ = __str__
|
1107 |
+
|
1108 |
+
def __eq__(self, other) -> bool:
|
1109 |
+
return self.value == other.value
|
1110 |
+
|
1111 |
+
def view(self):
|
1112 |
+
return self
|
1113 |
+
|
1114 |
+
df = DataFrame(index=[0, 1], columns=[0])
|
1115 |
+
df.iloc[1, 0] = TO(1)
|
1116 |
+
df.iloc[1, 0] = TO(2)
|
1117 |
+
|
1118 |
+
result = DataFrame(index=[0, 1], columns=[0])
|
1119 |
+
result.iloc[1, 0] = TO(2)
|
1120 |
+
|
1121 |
+
tm.assert_frame_equal(result, df)
|
1122 |
+
|
1123 |
+
# remains object dtype even after setting it back
|
1124 |
+
df = DataFrame(index=[0, 1], columns=[0])
|
1125 |
+
df.iloc[1, 0] = TO(1)
|
1126 |
+
df.iloc[1, 0] = np.nan
|
1127 |
+
result = DataFrame(index=[0, 1], columns=[0])
|
1128 |
+
|
1129 |
+
tm.assert_frame_equal(result, df)
|
1130 |
+
|
1131 |
+
def test_iloc_getitem_with_duplicates(self):
|
1132 |
+
df = DataFrame(
|
1133 |
+
np.random.default_rng(2).random((3, 3)),
|
1134 |
+
columns=list("ABC"),
|
1135 |
+
index=list("aab"),
|
1136 |
+
)
|
1137 |
+
|
1138 |
+
result = df.iloc[0]
|
1139 |
+
assert isinstance(result, Series)
|
1140 |
+
tm.assert_almost_equal(result.values, df.values[0])
|
1141 |
+
|
1142 |
+
result = df.T.iloc[:, 0]
|
1143 |
+
assert isinstance(result, Series)
|
1144 |
+
tm.assert_almost_equal(result.values, df.values[0])
|
1145 |
+
|
1146 |
+
def test_iloc_getitem_with_duplicates2(self):
|
1147 |
+
# GH#2259
|
1148 |
+
df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=[1, 1, 2])
|
1149 |
+
result = df.iloc[:, [0]]
|
1150 |
+
expected = df.take([0], axis=1)
|
1151 |
+
tm.assert_frame_equal(result, expected)
|
1152 |
+
|
1153 |
+
def test_iloc_interval(self):
|
1154 |
+
# GH#17130
|
1155 |
+
df = DataFrame({Interval(1, 2): [1, 2]})
|
1156 |
+
|
1157 |
+
result = df.iloc[0]
|
1158 |
+
expected = Series({Interval(1, 2): 1}, name=0)
|
1159 |
+
tm.assert_series_equal(result, expected)
|
1160 |
+
|
1161 |
+
result = df.iloc[:, 0]
|
1162 |
+
expected = Series([1, 2], name=Interval(1, 2))
|
1163 |
+
tm.assert_series_equal(result, expected)
|
1164 |
+
|
1165 |
+
result = df.copy()
|
1166 |
+
result.iloc[:, 0] += 1
|
1167 |
+
expected = DataFrame({Interval(1, 2): [2, 3]})
|
1168 |
+
tm.assert_frame_equal(result, expected)
|
1169 |
+
|
1170 |
+
@pytest.mark.parametrize("indexing_func", [list, np.array])
|
1171 |
+
@pytest.mark.parametrize("rhs_func", [list, np.array])
|
1172 |
+
def test_loc_setitem_boolean_list(self, rhs_func, indexing_func):
|
1173 |
+
# GH#20438 testing specifically list key, not arraylike
|
1174 |
+
ser = Series([0, 1, 2])
|
1175 |
+
ser.iloc[indexing_func([True, False, True])] = rhs_func([5, 10])
|
1176 |
+
expected = Series([5, 1, 10])
|
1177 |
+
tm.assert_series_equal(ser, expected)
|
1178 |
+
|
1179 |
+
df = DataFrame({"a": [0, 1, 2]})
|
1180 |
+
df.iloc[indexing_func([True, False, True])] = rhs_func([[5], [10]])
|
1181 |
+
expected = DataFrame({"a": [5, 1, 10]})
|
1182 |
+
tm.assert_frame_equal(df, expected)
|
1183 |
+
|
1184 |
+
def test_iloc_getitem_slice_negative_step_ea_block(self):
|
1185 |
+
# GH#44551
|
1186 |
+
df = DataFrame({"A": [1, 2, 3]}, dtype="Int64")
|
1187 |
+
|
1188 |
+
res = df.iloc[:, ::-1]
|
1189 |
+
tm.assert_frame_equal(res, df)
|
1190 |
+
|
1191 |
+
df["B"] = "foo"
|
1192 |
+
res = df.iloc[:, ::-1]
|
1193 |
+
expected = DataFrame({"B": df["B"], "A": df["A"]})
|
1194 |
+
tm.assert_frame_equal(res, expected)
|
1195 |
+
|
1196 |
+
def test_iloc_setitem_2d_ndarray_into_ea_block(self):
|
1197 |
+
# GH#44703
|
1198 |
+
df = DataFrame({"status": ["a", "b", "c"]}, dtype="category")
|
1199 |
+
df.iloc[np.array([0, 1]), np.array([0])] = np.array([["a"], ["a"]])
|
1200 |
+
|
1201 |
+
expected = DataFrame({"status": ["a", "a", "c"]}, dtype=df["status"].dtype)
|
1202 |
+
tm.assert_frame_equal(df, expected)
|
1203 |
+
|
1204 |
+
@td.skip_array_manager_not_yet_implemented
|
1205 |
+
def test_iloc_getitem_int_single_ea_block_view(self):
|
1206 |
+
# GH#45241
|
1207 |
+
# TODO: make an extension interface test for this?
|
1208 |
+
arr = interval_range(1, 10.0)._values
|
1209 |
+
df = DataFrame(arr)
|
1210 |
+
|
1211 |
+
# ser should be a *view* on the DataFrame data
|
1212 |
+
ser = df.iloc[2]
|
1213 |
+
|
1214 |
+
# if we have a view, then changing arr[2] should also change ser[0]
|
1215 |
+
assert arr[2] != arr[-1] # otherwise the rest isn't meaningful
|
1216 |
+
arr[2] = arr[-1]
|
1217 |
+
assert ser[0] == arr[-1]
|
1218 |
+
|
1219 |
+
def test_iloc_setitem_multicolumn_to_datetime(self):
|
1220 |
+
# GH#20511
|
1221 |
+
df = DataFrame({"A": ["2022-01-01", "2022-01-02"], "B": ["2021", "2022"]})
|
1222 |
+
|
1223 |
+
df.iloc[:, [0]] = DataFrame({"A": to_datetime(["2021", "2022"])})
|
1224 |
+
expected = DataFrame(
|
1225 |
+
{
|
1226 |
+
"A": [
|
1227 |
+
Timestamp("2021-01-01 00:00:00"),
|
1228 |
+
Timestamp("2022-01-01 00:00:00"),
|
1229 |
+
],
|
1230 |
+
"B": ["2021", "2022"],
|
1231 |
+
}
|
1232 |
+
)
|
1233 |
+
tm.assert_frame_equal(df, expected, check_dtype=False)
|
1234 |
+
|
1235 |
+
|
1236 |
+
class TestILocErrors:
|
1237 |
+
# NB: this test should work for _any_ Series we can pass as
|
1238 |
+
# series_with_simple_index
|
1239 |
+
def test_iloc_float_raises(
|
1240 |
+
self, series_with_simple_index, frame_or_series, warn_copy_on_write
|
1241 |
+
):
|
1242 |
+
# GH#4892
|
1243 |
+
# float_indexers should raise exceptions
|
1244 |
+
# on appropriate Index types & accessors
|
1245 |
+
# this duplicates the code below
|
1246 |
+
# but is specifically testing for the error
|
1247 |
+
# message
|
1248 |
+
|
1249 |
+
obj = series_with_simple_index
|
1250 |
+
if frame_or_series is DataFrame:
|
1251 |
+
obj = obj.to_frame()
|
1252 |
+
|
1253 |
+
msg = "Cannot index by location index with a non-integer key"
|
1254 |
+
with pytest.raises(TypeError, match=msg):
|
1255 |
+
obj.iloc[3.0]
|
1256 |
+
|
1257 |
+
with pytest.raises(IndexError, match=_slice_iloc_msg):
|
1258 |
+
with tm.assert_cow_warning(
|
1259 |
+
warn_copy_on_write and frame_or_series is DataFrame
|
1260 |
+
):
|
1261 |
+
obj.iloc[3.0] = 0
|
1262 |
+
|
1263 |
+
def test_iloc_getitem_setitem_fancy_exceptions(self, float_frame):
|
1264 |
+
with pytest.raises(IndexingError, match="Too many indexers"):
|
1265 |
+
float_frame.iloc[:, :, :]
|
1266 |
+
|
1267 |
+
with pytest.raises(IndexError, match="too many indices for array"):
|
1268 |
+
# GH#32257 we let numpy do validation, get their exception
|
1269 |
+
float_frame.iloc[:, :, :] = 1
|
1270 |
+
|
1271 |
+
def test_iloc_frame_indexer(self):
|
1272 |
+
# GH#39004
|
1273 |
+
df = DataFrame({"a": [1, 2, 3]})
|
1274 |
+
indexer = DataFrame({"a": [True, False, True]})
|
1275 |
+
msg = "DataFrame indexer for .iloc is not supported. Consider using .loc"
|
1276 |
+
with pytest.raises(TypeError, match=msg):
|
1277 |
+
df.iloc[indexer] = 1
|
1278 |
+
|
1279 |
+
msg = (
|
1280 |
+
"DataFrame indexer is not allowed for .iloc\n"
|
1281 |
+
"Consider using .loc for automatic alignment."
|
1282 |
+
)
|
1283 |
+
with pytest.raises(IndexError, match=msg):
|
1284 |
+
df.iloc[indexer]
|
1285 |
+
|
1286 |
+
|
1287 |
+
class TestILocSetItemDuplicateColumns:
|
1288 |
+
def test_iloc_setitem_scalar_duplicate_columns(self):
|
1289 |
+
# GH#15686, duplicate columns and mixed dtype
|
1290 |
+
df1 = DataFrame([{"A": None, "B": 1}, {"A": 2, "B": 2}])
|
1291 |
+
df2 = DataFrame([{"A": 3, "B": 3}, {"A": 4, "B": 4}])
|
1292 |
+
df = concat([df1, df2], axis=1)
|
1293 |
+
df.iloc[0, 0] = -1
|
1294 |
+
|
1295 |
+
assert df.iloc[0, 0] == -1
|
1296 |
+
assert df.iloc[0, 2] == 3
|
1297 |
+
assert df.dtypes.iloc[2] == np.int64
|
1298 |
+
|
1299 |
+
def test_iloc_setitem_list_duplicate_columns(self):
|
1300 |
+
# GH#22036 setting with same-sized list
|
1301 |
+
df = DataFrame([[0, "str", "str2"]], columns=["a", "b", "b"])
|
1302 |
+
|
1303 |
+
df.iloc[:, 2] = ["str3"]
|
1304 |
+
|
1305 |
+
expected = DataFrame([[0, "str", "str3"]], columns=["a", "b", "b"])
|
1306 |
+
tm.assert_frame_equal(df, expected)
|
1307 |
+
|
1308 |
+
def test_iloc_setitem_series_duplicate_columns(self):
|
1309 |
+
df = DataFrame(
|
1310 |
+
np.arange(8, dtype=np.int64).reshape(2, 4), columns=["A", "B", "A", "B"]
|
1311 |
+
)
|
1312 |
+
df.iloc[:, 0] = df.iloc[:, 0].astype(np.float64)
|
1313 |
+
assert df.dtypes.iloc[2] == np.int64
|
1314 |
+
|
1315 |
+
@pytest.mark.parametrize(
|
1316 |
+
["dtypes", "init_value", "expected_value"],
|
1317 |
+
[("int64", "0", 0), ("float", "1.2", 1.2)],
|
1318 |
+
)
|
1319 |
+
def test_iloc_setitem_dtypes_duplicate_columns(
|
1320 |
+
self, dtypes, init_value, expected_value
|
1321 |
+
):
|
1322 |
+
# GH#22035
|
1323 |
+
df = DataFrame(
|
1324 |
+
[[init_value, "str", "str2"]], columns=["a", "b", "b"], dtype=object
|
1325 |
+
)
|
1326 |
+
|
1327 |
+
# with the enforcement of GH#45333 in 2.0, this sets values inplace,
|
1328 |
+
# so we retain object dtype
|
1329 |
+
df.iloc[:, 0] = df.iloc[:, 0].astype(dtypes)
|
1330 |
+
|
1331 |
+
expected_df = DataFrame(
|
1332 |
+
[[expected_value, "str", "str2"]],
|
1333 |
+
columns=["a", "b", "b"],
|
1334 |
+
dtype=object,
|
1335 |
+
)
|
1336 |
+
tm.assert_frame_equal(df, expected_df)
|
1337 |
+
|
1338 |
+
|
1339 |
+
class TestILocCallable:
|
1340 |
+
def test_frame_iloc_getitem_callable(self):
|
1341 |
+
# GH#11485
|
1342 |
+
df = DataFrame({"X": [1, 2, 3, 4], "Y": list("aabb")}, index=list("ABCD"))
|
1343 |
+
|
1344 |
+
# return location
|
1345 |
+
res = df.iloc[lambda x: [1, 3]]
|
1346 |
+
tm.assert_frame_equal(res, df.iloc[[1, 3]])
|
1347 |
+
|
1348 |
+
res = df.iloc[lambda x: [1, 3], :]
|
1349 |
+
tm.assert_frame_equal(res, df.iloc[[1, 3], :])
|
1350 |
+
|
1351 |
+
res = df.iloc[lambda x: [1, 3], lambda x: 0]
|
1352 |
+
tm.assert_series_equal(res, df.iloc[[1, 3], 0])
|
1353 |
+
|
1354 |
+
res = df.iloc[lambda x: [1, 3], lambda x: [0]]
|
1355 |
+
tm.assert_frame_equal(res, df.iloc[[1, 3], [0]])
|
1356 |
+
|
1357 |
+
# mixture
|
1358 |
+
res = df.iloc[[1, 3], lambda x: 0]
|
1359 |
+
tm.assert_series_equal(res, df.iloc[[1, 3], 0])
|
1360 |
+
|
1361 |
+
res = df.iloc[[1, 3], lambda x: [0]]
|
1362 |
+
tm.assert_frame_equal(res, df.iloc[[1, 3], [0]])
|
1363 |
+
|
1364 |
+
res = df.iloc[lambda x: [1, 3], 0]
|
1365 |
+
tm.assert_series_equal(res, df.iloc[[1, 3], 0])
|
1366 |
+
|
1367 |
+
res = df.iloc[lambda x: [1, 3], [0]]
|
1368 |
+
tm.assert_frame_equal(res, df.iloc[[1, 3], [0]])
|
1369 |
+
|
1370 |
+
def test_frame_iloc_setitem_callable(self):
|
1371 |
+
# GH#11485
|
1372 |
+
df = DataFrame(
|
1373 |
+
{"X": [1, 2, 3, 4], "Y": Series(list("aabb"), dtype=object)},
|
1374 |
+
index=list("ABCD"),
|
1375 |
+
)
|
1376 |
+
|
1377 |
+
# return location
|
1378 |
+
res = df.copy()
|
1379 |
+
res.iloc[lambda x: [1, 3]] = 0
|
1380 |
+
exp = df.copy()
|
1381 |
+
exp.iloc[[1, 3]] = 0
|
1382 |
+
tm.assert_frame_equal(res, exp)
|
1383 |
+
|
1384 |
+
res = df.copy()
|
1385 |
+
res.iloc[lambda x: [1, 3], :] = -1
|
1386 |
+
exp = df.copy()
|
1387 |
+
exp.iloc[[1, 3], :] = -1
|
1388 |
+
tm.assert_frame_equal(res, exp)
|
1389 |
+
|
1390 |
+
res = df.copy()
|
1391 |
+
res.iloc[lambda x: [1, 3], lambda x: 0] = 5
|
1392 |
+
exp = df.copy()
|
1393 |
+
exp.iloc[[1, 3], 0] = 5
|
1394 |
+
tm.assert_frame_equal(res, exp)
|
1395 |
+
|
1396 |
+
res = df.copy()
|
1397 |
+
res.iloc[lambda x: [1, 3], lambda x: [0]] = 25
|
1398 |
+
exp = df.copy()
|
1399 |
+
exp.iloc[[1, 3], [0]] = 25
|
1400 |
+
tm.assert_frame_equal(res, exp)
|
1401 |
+
|
1402 |
+
# mixture
|
1403 |
+
res = df.copy()
|
1404 |
+
res.iloc[[1, 3], lambda x: 0] = -3
|
1405 |
+
exp = df.copy()
|
1406 |
+
exp.iloc[[1, 3], 0] = -3
|
1407 |
+
tm.assert_frame_equal(res, exp)
|
1408 |
+
|
1409 |
+
res = df.copy()
|
1410 |
+
res.iloc[[1, 3], lambda x: [0]] = -5
|
1411 |
+
exp = df.copy()
|
1412 |
+
exp.iloc[[1, 3], [0]] = -5
|
1413 |
+
tm.assert_frame_equal(res, exp)
|
1414 |
+
|
1415 |
+
res = df.copy()
|
1416 |
+
res.iloc[lambda x: [1, 3], 0] = 10
|
1417 |
+
exp = df.copy()
|
1418 |
+
exp.iloc[[1, 3], 0] = 10
|
1419 |
+
tm.assert_frame_equal(res, exp)
|
1420 |
+
|
1421 |
+
res = df.copy()
|
1422 |
+
res.iloc[lambda x: [1, 3], [0]] = [-5, -5]
|
1423 |
+
exp = df.copy()
|
1424 |
+
exp.iloc[[1, 3], [0]] = [-5, -5]
|
1425 |
+
tm.assert_frame_equal(res, exp)
|
1426 |
+
|
1427 |
+
|
1428 |
+
class TestILocSeries:
|
1429 |
+
def test_iloc(self, using_copy_on_write, warn_copy_on_write):
|
1430 |
+
ser = Series(
|
1431 |
+
np.random.default_rng(2).standard_normal(10), index=list(range(0, 20, 2))
|
1432 |
+
)
|
1433 |
+
ser_original = ser.copy()
|
1434 |
+
|
1435 |
+
for i in range(len(ser)):
|
1436 |
+
result = ser.iloc[i]
|
1437 |
+
exp = ser[ser.index[i]]
|
1438 |
+
tm.assert_almost_equal(result, exp)
|
1439 |
+
|
1440 |
+
# pass a slice
|
1441 |
+
result = ser.iloc[slice(1, 3)]
|
1442 |
+
expected = ser.loc[2:4]
|
1443 |
+
tm.assert_series_equal(result, expected)
|
1444 |
+
|
1445 |
+
# test slice is a view
|
1446 |
+
with tm.assert_produces_warning(None):
|
1447 |
+
# GH#45324 make sure we aren't giving a spurious FutureWarning
|
1448 |
+
with tm.assert_cow_warning(warn_copy_on_write):
|
1449 |
+
result[:] = 0
|
1450 |
+
if using_copy_on_write:
|
1451 |
+
tm.assert_series_equal(ser, ser_original)
|
1452 |
+
else:
|
1453 |
+
assert (ser.iloc[1:3] == 0).all()
|
1454 |
+
|
1455 |
+
# list of integers
|
1456 |
+
result = ser.iloc[[0, 2, 3, 4, 5]]
|
1457 |
+
expected = ser.reindex(ser.index[[0, 2, 3, 4, 5]])
|
1458 |
+
tm.assert_series_equal(result, expected)
|
1459 |
+
|
1460 |
+
def test_iloc_getitem_nonunique(self):
|
1461 |
+
ser = Series([0, 1, 2], index=[0, 1, 0])
|
1462 |
+
assert ser.iloc[2] == 2
|
1463 |
+
|
1464 |
+
def test_iloc_setitem_pure_position_based(self):
|
1465 |
+
# GH#22046
|
1466 |
+
ser1 = Series([1, 2, 3])
|
1467 |
+
ser2 = Series([4, 5, 6], index=[1, 0, 2])
|
1468 |
+
ser1.iloc[1:3] = ser2.iloc[1:3]
|
1469 |
+
expected = Series([1, 5, 6])
|
1470 |
+
tm.assert_series_equal(ser1, expected)
|
1471 |
+
|
1472 |
+
def test_iloc_nullable_int64_size_1_nan(self):
|
1473 |
+
# GH 31861
|
1474 |
+
result = DataFrame({"a": ["test"], "b": [np.nan]})
|
1475 |
+
with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):
|
1476 |
+
result.loc[:, "b"] = result.loc[:, "b"].astype("Int64")
|
1477 |
+
expected = DataFrame({"a": ["test"], "b": array([NA], dtype="Int64")})
|
1478 |
+
tm.assert_frame_equal(result, expected)
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/test_indexers.py
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Tests aimed at pandas.core.indexers
|
2 |
+
import numpy as np
|
3 |
+
import pytest
|
4 |
+
|
5 |
+
from pandas.core.indexers import (
|
6 |
+
is_scalar_indexer,
|
7 |
+
length_of_indexer,
|
8 |
+
validate_indices,
|
9 |
+
)
|
10 |
+
|
11 |
+
|
12 |
+
def test_length_of_indexer():
|
13 |
+
arr = np.zeros(4, dtype=bool)
|
14 |
+
arr[0] = 1
|
15 |
+
result = length_of_indexer(arr)
|
16 |
+
assert result == 1
|
17 |
+
|
18 |
+
|
19 |
+
def test_is_scalar_indexer():
|
20 |
+
indexer = (0, 1)
|
21 |
+
assert is_scalar_indexer(indexer, 2)
|
22 |
+
assert not is_scalar_indexer(indexer[0], 2)
|
23 |
+
|
24 |
+
indexer = (np.array([2]), 1)
|
25 |
+
assert not is_scalar_indexer(indexer, 2)
|
26 |
+
|
27 |
+
indexer = (np.array([2]), np.array([3]))
|
28 |
+
assert not is_scalar_indexer(indexer, 2)
|
29 |
+
|
30 |
+
indexer = (np.array([2]), np.array([3, 4]))
|
31 |
+
assert not is_scalar_indexer(indexer, 2)
|
32 |
+
|
33 |
+
assert not is_scalar_indexer(slice(None), 1)
|
34 |
+
|
35 |
+
indexer = 0
|
36 |
+
assert is_scalar_indexer(indexer, 1)
|
37 |
+
|
38 |
+
indexer = (0,)
|
39 |
+
assert is_scalar_indexer(indexer, 1)
|
40 |
+
|
41 |
+
|
42 |
+
class TestValidateIndices:
|
43 |
+
def test_validate_indices_ok(self):
|
44 |
+
indices = np.asarray([0, 1])
|
45 |
+
validate_indices(indices, 2)
|
46 |
+
validate_indices(indices[:0], 0)
|
47 |
+
validate_indices(np.array([-1, -1]), 0)
|
48 |
+
|
49 |
+
def test_validate_indices_low(self):
|
50 |
+
indices = np.asarray([0, -2])
|
51 |
+
with pytest.raises(ValueError, match="'indices' contains"):
|
52 |
+
validate_indices(indices, 2)
|
53 |
+
|
54 |
+
def test_validate_indices_high(self):
|
55 |
+
indices = np.asarray([0, 1, 2])
|
56 |
+
with pytest.raises(IndexError, match="indices are out"):
|
57 |
+
validate_indices(indices, 2)
|
58 |
+
|
59 |
+
def test_validate_indices_empty(self):
|
60 |
+
with pytest.raises(IndexError, match="indices are out"):
|
61 |
+
validate_indices(np.array([0, 1]), 0)
|
venv/lib/python3.10/site-packages/pandas/tests/indexing/test_indexing.py
ADDED
@@ -0,0 +1,1157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" test fancy indexing & misc """
|
2 |
+
|
3 |
+
import array
|
4 |
+
from datetime import datetime
|
5 |
+
import re
|
6 |
+
import weakref
|
7 |
+
|
8 |
+
import numpy as np
|
9 |
+
import pytest
|
10 |
+
|
11 |
+
from pandas._config import using_pyarrow_string_dtype
|
12 |
+
|
13 |
+
from pandas.errors import IndexingError
|
14 |
+
|
15 |
+
from pandas.core.dtypes.common import (
|
16 |
+
is_float_dtype,
|
17 |
+
is_integer_dtype,
|
18 |
+
is_object_dtype,
|
19 |
+
)
|
20 |
+
|
21 |
+
import pandas as pd
|
22 |
+
from pandas import (
|
23 |
+
DataFrame,
|
24 |
+
Index,
|
25 |
+
NaT,
|
26 |
+
Series,
|
27 |
+
date_range,
|
28 |
+
offsets,
|
29 |
+
timedelta_range,
|
30 |
+
)
|
31 |
+
import pandas._testing as tm
|
32 |
+
from pandas.tests.indexing.common import _mklbl
|
33 |
+
from pandas.tests.indexing.test_floats import gen_obj
|
34 |
+
|
35 |
+
# ------------------------------------------------------------------------
|
36 |
+
# Indexing test cases
|
37 |
+
|
38 |
+
|
39 |
+
class TestFancy:
|
40 |
+
"""pure get/set item & fancy indexing"""
|
41 |
+
|
42 |
+
def test_setitem_ndarray_1d(self):
|
43 |
+
# GH5508
|
44 |
+
|
45 |
+
# len of indexer vs length of the 1d ndarray
|
46 |
+
df = DataFrame(index=Index(np.arange(1, 11), dtype=np.int64))
|
47 |
+
df["foo"] = np.zeros(10, dtype=np.float64)
|
48 |
+
df["bar"] = np.zeros(10, dtype=complex)
|
49 |
+
|
50 |
+
# invalid
|
51 |
+
msg = "Must have equal len keys and value when setting with an iterable"
|
52 |
+
with pytest.raises(ValueError, match=msg):
|
53 |
+
df.loc[df.index[2:5], "bar"] = np.array([2.33j, 1.23 + 0.1j, 2.2, 1.0])
|
54 |
+
|
55 |
+
# valid
|
56 |
+
df.loc[df.index[2:6], "bar"] = np.array([2.33j, 1.23 + 0.1j, 2.2, 1.0])
|
57 |
+
|
58 |
+
result = df.loc[df.index[2:6], "bar"]
|
59 |
+
expected = Series(
|
60 |
+
[2.33j, 1.23 + 0.1j, 2.2, 1.0], index=[3, 4, 5, 6], name="bar"
|
61 |
+
)
|
62 |
+
tm.assert_series_equal(result, expected)
|
63 |
+
|
64 |
+
def test_setitem_ndarray_1d_2(self):
|
65 |
+
# GH5508
|
66 |
+
|
67 |
+
# dtype getting changed?
|
68 |
+
df = DataFrame(index=Index(np.arange(1, 11)))
|
69 |
+
df["foo"] = np.zeros(10, dtype=np.float64)
|
70 |
+
df["bar"] = np.zeros(10, dtype=complex)
|
71 |
+
|
72 |
+
msg = "Must have equal len keys and value when setting with an iterable"
|
73 |
+
with pytest.raises(ValueError, match=msg):
|
74 |
+
df[2:5] = np.arange(1, 4) * 1j
|
75 |
+
|
76 |
+
@pytest.mark.filterwarnings(
|
77 |
+
"ignore:Series.__getitem__ treating keys as positions is deprecated:"
|
78 |
+
"FutureWarning"
|
79 |
+
)
|
80 |
+
def test_getitem_ndarray_3d(
|
81 |
+
self, index, frame_or_series, indexer_sli, using_array_manager
|
82 |
+
):
|
83 |
+
# GH 25567
|
84 |
+
obj = gen_obj(frame_or_series, index)
|
85 |
+
idxr = indexer_sli(obj)
|
86 |
+
nd3 = np.random.default_rng(2).integers(5, size=(2, 2, 2))
|
87 |
+
|
88 |
+
msgs = []
|
89 |
+
if frame_or_series is Series and indexer_sli in [tm.setitem, tm.iloc]:
|
90 |
+
msgs.append(r"Wrong number of dimensions. values.ndim > ndim \[3 > 1\]")
|
91 |
+
if using_array_manager:
|
92 |
+
msgs.append("Passed array should be 1-dimensional")
|
93 |
+
if frame_or_series is Series or indexer_sli is tm.iloc:
|
94 |
+
msgs.append(r"Buffer has wrong number of dimensions \(expected 1, got 3\)")
|
95 |
+
if using_array_manager:
|
96 |
+
msgs.append("indexer should be 1-dimensional")
|
97 |
+
if indexer_sli is tm.loc or (
|
98 |
+
frame_or_series is Series and indexer_sli is tm.setitem
|
99 |
+
):
|
100 |
+
msgs.append("Cannot index with multidimensional key")
|
101 |
+
if frame_or_series is DataFrame and indexer_sli is tm.setitem:
|
102 |
+
msgs.append("Index data must be 1-dimensional")
|
103 |
+
if isinstance(index, pd.IntervalIndex) and indexer_sli is tm.iloc:
|
104 |
+
msgs.append("Index data must be 1-dimensional")
|
105 |
+
if isinstance(index, (pd.TimedeltaIndex, pd.DatetimeIndex, pd.PeriodIndex)):
|
106 |
+
msgs.append("Data must be 1-dimensional")
|
107 |
+
if len(index) == 0 or isinstance(index, pd.MultiIndex):
|
108 |
+
msgs.append("positional indexers are out-of-bounds")
|
109 |
+
if type(index) is Index and not isinstance(index._values, np.ndarray):
|
110 |
+
# e.g. Int64
|
111 |
+
msgs.append("values must be a 1D array")
|
112 |
+
|
113 |
+
# string[pyarrow]
|
114 |
+
msgs.append("only handle 1-dimensional arrays")
|
115 |
+
|
116 |
+
msg = "|".join(msgs)
|
117 |
+
|
118 |
+
potential_errors = (IndexError, ValueError, NotImplementedError)
|
119 |
+
with pytest.raises(potential_errors, match=msg):
|
120 |
+
idxr[nd3]
|
121 |
+
|
122 |
+
@pytest.mark.filterwarnings(
|
123 |
+
"ignore:Series.__setitem__ treating keys as positions is deprecated:"
|
124 |
+
"FutureWarning"
|
125 |
+
)
|
126 |
+
def test_setitem_ndarray_3d(self, index, frame_or_series, indexer_sli):
|
127 |
+
# GH 25567
|
128 |
+
obj = gen_obj(frame_or_series, index)
|
129 |
+
idxr = indexer_sli(obj)
|
130 |
+
nd3 = np.random.default_rng(2).integers(5, size=(2, 2, 2))
|
131 |
+
|
132 |
+
if indexer_sli is tm.iloc:
|
133 |
+
err = ValueError
|
134 |
+
msg = f"Cannot set values with ndim > {obj.ndim}"
|
135 |
+
else:
|
136 |
+
err = ValueError
|
137 |
+
msg = "|".join(
|
138 |
+
[
|
139 |
+
r"Buffer has wrong number of dimensions \(expected 1, got 3\)",
|
140 |
+
"Cannot set values with ndim > 1",
|
141 |
+
"Index data must be 1-dimensional",
|
142 |
+
"Data must be 1-dimensional",
|
143 |
+
"Array conditional must be same shape as self",
|
144 |
+
]
|
145 |
+
)
|
146 |
+
|
147 |
+
with pytest.raises(err, match=msg):
|
148 |
+
idxr[nd3] = 0
|
149 |
+
|
150 |
+
def test_getitem_ndarray_0d(self):
|
151 |
+
# GH#24924
|
152 |
+
key = np.array(0)
|
153 |
+
|
154 |
+
# dataframe __getitem__
|
155 |
+
df = DataFrame([[1, 2], [3, 4]])
|
156 |
+
result = df[key]
|
157 |
+
expected = Series([1, 3], name=0)
|
158 |
+
tm.assert_series_equal(result, expected)
|
159 |
+
|
160 |
+
# series __getitem__
|
161 |
+
ser = Series([1, 2])
|
162 |
+
result = ser[key]
|
163 |
+
assert result == 1
|
164 |
+
|
165 |
+
def test_inf_upcast(self):
|
166 |
+
# GH 16957
|
167 |
+
# We should be able to use np.inf as a key
|
168 |
+
# np.inf should cause an index to convert to float
|
169 |
+
|
170 |
+
# Test with np.inf in rows
|
171 |
+
df = DataFrame(columns=[0])
|
172 |
+
df.loc[1] = 1
|
173 |
+
df.loc[2] = 2
|
174 |
+
df.loc[np.inf] = 3
|
175 |
+
|
176 |
+
# make sure we can look up the value
|
177 |
+
assert df.loc[np.inf, 0] == 3
|
178 |
+
|
179 |
+
result = df.index
|
180 |
+
expected = Index([1, 2, np.inf], dtype=np.float64)
|
181 |
+
tm.assert_index_equal(result, expected)
|
182 |
+
|
183 |
+
def test_setitem_dtype_upcast(self):
|
184 |
+
# GH3216
|
185 |
+
df = DataFrame([{"a": 1}, {"a": 3, "b": 2}])
|
186 |
+
df["c"] = np.nan
|
187 |
+
assert df["c"].dtype == np.float64
|
188 |
+
|
189 |
+
with tm.assert_produces_warning(
|
190 |
+
FutureWarning, match="item of incompatible dtype"
|
191 |
+
):
|
192 |
+
df.loc[0, "c"] = "foo"
|
193 |
+
expected = DataFrame(
|
194 |
+
{"a": [1, 3], "b": [np.nan, 2], "c": Series(["foo", np.nan], dtype=object)}
|
195 |
+
)
|
196 |
+
tm.assert_frame_equal(df, expected)
|
197 |
+
|
198 |
+
@pytest.mark.parametrize("val", [3.14, "wxyz"])
|
199 |
+
def test_setitem_dtype_upcast2(self, val):
|
200 |
+
# GH10280
|
201 |
+
df = DataFrame(
|
202 |
+
np.arange(6, dtype="int64").reshape(2, 3),
|
203 |
+
index=list("ab"),
|
204 |
+
columns=["foo", "bar", "baz"],
|
205 |
+
)
|
206 |
+
|
207 |
+
left = df.copy()
|
208 |
+
with tm.assert_produces_warning(
|
209 |
+
FutureWarning, match="item of incompatible dtype"
|
210 |
+
):
|
211 |
+
left.loc["a", "bar"] = val
|
212 |
+
right = DataFrame(
|
213 |
+
[[0, val, 2], [3, 4, 5]],
|
214 |
+
index=list("ab"),
|
215 |
+
columns=["foo", "bar", "baz"],
|
216 |
+
)
|
217 |
+
|
218 |
+
tm.assert_frame_equal(left, right)
|
219 |
+
assert is_integer_dtype(left["foo"])
|
220 |
+
assert is_integer_dtype(left["baz"])
|
221 |
+
|
222 |
+
def test_setitem_dtype_upcast3(self):
|
223 |
+
left = DataFrame(
|
224 |
+
np.arange(6, dtype="int64").reshape(2, 3) / 10.0,
|
225 |
+
index=list("ab"),
|
226 |
+
columns=["foo", "bar", "baz"],
|
227 |
+
)
|
228 |
+
with tm.assert_produces_warning(
|
229 |
+
FutureWarning, match="item of incompatible dtype"
|
230 |
+
):
|
231 |
+
left.loc["a", "bar"] = "wxyz"
|
232 |
+
|
233 |
+
right = DataFrame(
|
234 |
+
[[0, "wxyz", 0.2], [0.3, 0.4, 0.5]],
|
235 |
+
index=list("ab"),
|
236 |
+
columns=["foo", "bar", "baz"],
|
237 |
+
)
|
238 |
+
|
239 |
+
tm.assert_frame_equal(left, right)
|
240 |
+
assert is_float_dtype(left["foo"])
|
241 |
+
assert is_float_dtype(left["baz"])
|
242 |
+
|
243 |
+
def test_dups_fancy_indexing(self):
|
244 |
+
# GH 3455
|
245 |
+
|
246 |
+
df = DataFrame(np.eye(3), columns=["a", "a", "b"])
|
247 |
+
result = df[["b", "a"]].columns
|
248 |
+
expected = Index(["b", "a", "a"])
|
249 |
+
tm.assert_index_equal(result, expected)
|
250 |
+
|
251 |
+
def test_dups_fancy_indexing_across_dtypes(self):
|
252 |
+
# across dtypes
|
253 |
+
df = DataFrame([[1, 2, 1.0, 2.0, 3.0, "foo", "bar"]], columns=list("aaaaaaa"))
|
254 |
+
result = DataFrame([[1, 2, 1.0, 2.0, 3.0, "foo", "bar"]])
|
255 |
+
result.columns = list("aaaaaaa") # GH#3468
|
256 |
+
|
257 |
+
# GH#3509 smoke tests for indexing with duplicate columns
|
258 |
+
df.iloc[:, 4]
|
259 |
+
result.iloc[:, 4]
|
260 |
+
|
261 |
+
tm.assert_frame_equal(df, result)
|
262 |
+
|
263 |
+
def test_dups_fancy_indexing_not_in_order(self):
|
264 |
+
# GH 3561, dups not in selected order
|
265 |
+
df = DataFrame(
|
266 |
+
{"test": [5, 7, 9, 11], "test1": [4.0, 5, 6, 7], "other": list("abcd")},
|
267 |
+
index=["A", "A", "B", "C"],
|
268 |
+
)
|
269 |
+
rows = ["C", "B"]
|
270 |
+
expected = DataFrame(
|
271 |
+
{"test": [11, 9], "test1": [7.0, 6], "other": ["d", "c"]}, index=rows
|
272 |
+
)
|
273 |
+
result = df.loc[rows]
|
274 |
+
tm.assert_frame_equal(result, expected)
|
275 |
+
|
276 |
+
result = df.loc[Index(rows)]
|
277 |
+
tm.assert_frame_equal(result, expected)
|
278 |
+
|
279 |
+
rows = ["C", "B", "E"]
|
280 |
+
with pytest.raises(KeyError, match="not in index"):
|
281 |
+
df.loc[rows]
|
282 |
+
|
283 |
+
# see GH5553, make sure we use the right indexer
|
284 |
+
rows = ["F", "G", "H", "C", "B", "E"]
|
285 |
+
with pytest.raises(KeyError, match="not in index"):
|
286 |
+
df.loc[rows]
|
287 |
+
|
288 |
+
def test_dups_fancy_indexing_only_missing_label(self, using_infer_string):
|
289 |
+
# List containing only missing label
|
290 |
+
dfnu = DataFrame(
|
291 |
+
np.random.default_rng(2).standard_normal((5, 3)), index=list("AABCD")
|
292 |
+
)
|
293 |
+
if using_infer_string:
|
294 |
+
with pytest.raises(
|
295 |
+
KeyError,
|
296 |
+
match=re.escape(
|
297 |
+
"\"None of [Index(['E'], dtype='string')] are in the [index]\""
|
298 |
+
),
|
299 |
+
):
|
300 |
+
dfnu.loc[["E"]]
|
301 |
+
else:
|
302 |
+
with pytest.raises(
|
303 |
+
KeyError,
|
304 |
+
match=re.escape(
|
305 |
+
"\"None of [Index(['E'], dtype='object')] are in the [index]\""
|
306 |
+
),
|
307 |
+
):
|
308 |
+
dfnu.loc[["E"]]
|
309 |
+
|
310 |
+
@pytest.mark.parametrize("vals", [[0, 1, 2], list("abc")])
|
311 |
+
def test_dups_fancy_indexing_missing_label(self, vals):
|
312 |
+
# GH 4619; duplicate indexer with missing label
|
313 |
+
df = DataFrame({"A": vals})
|
314 |
+
with pytest.raises(KeyError, match="not in index"):
|
315 |
+
df.loc[[0, 8, 0]]
|
316 |
+
|
317 |
+
def test_dups_fancy_indexing_non_unique(self):
|
318 |
+
# non unique with non unique selector
|
319 |
+
df = DataFrame({"test": [5, 7, 9, 11]}, index=["A", "A", "B", "C"])
|
320 |
+
with pytest.raises(KeyError, match="not in index"):
|
321 |
+
df.loc[["A", "A", "E"]]
|
322 |
+
|
323 |
+
def test_dups_fancy_indexing2(self):
|
324 |
+
# GH 5835
|
325 |
+
# dups on index and missing values
|
326 |
+
df = DataFrame(
|
327 |
+
np.random.default_rng(2).standard_normal((5, 5)),
|
328 |
+
columns=["A", "B", "B", "B", "A"],
|
329 |
+
)
|
330 |
+
|
331 |
+
with pytest.raises(KeyError, match="not in index"):
|
332 |
+
df.loc[:, ["A", "B", "C"]]
|
333 |
+
|
334 |
+
def test_dups_fancy_indexing3(self):
|
335 |
+
# GH 6504, multi-axis indexing
|
336 |
+
df = DataFrame(
|
337 |
+
np.random.default_rng(2).standard_normal((9, 2)),
|
338 |
+
index=[1, 1, 1, 2, 2, 2, 3, 3, 3],
|
339 |
+
columns=["a", "b"],
|
340 |
+
)
|
341 |
+
|
342 |
+
expected = df.iloc[0:6]
|
343 |
+
result = df.loc[[1, 2]]
|
344 |
+
tm.assert_frame_equal(result, expected)
|
345 |
+
|
346 |
+
expected = df
|
347 |
+
result = df.loc[:, ["a", "b"]]
|
348 |
+
tm.assert_frame_equal(result, expected)
|
349 |
+
|
350 |
+
expected = df.iloc[0:6, :]
|
351 |
+
result = df.loc[[1, 2], ["a", "b"]]
|
352 |
+
tm.assert_frame_equal(result, expected)
|
353 |
+
|
354 |
+
def test_duplicate_int_indexing(self, indexer_sl):
|
355 |
+
# GH 17347
|
356 |
+
ser = Series(range(3), index=[1, 1, 3])
|
357 |
+
expected = Series(range(2), index=[1, 1])
|
358 |
+
result = indexer_sl(ser)[[1]]
|
359 |
+
tm.assert_series_equal(result, expected)
|
360 |
+
|
361 |
+
def test_indexing_mixed_frame_bug(self):
|
362 |
+
# GH3492
|
363 |
+
df = DataFrame(
|
364 |
+
{"a": {1: "aaa", 2: "bbb", 3: "ccc"}, "b": {1: 111, 2: 222, 3: 333}}
|
365 |
+
)
|
366 |
+
|
367 |
+
# this works, new column is created correctly
|
368 |
+
df["test"] = df["a"].apply(lambda x: "_" if x == "aaa" else x)
|
369 |
+
|
370 |
+
# this does not work, ie column test is not changed
|
371 |
+
idx = df["test"] == "_"
|
372 |
+
temp = df.loc[idx, "a"].apply(lambda x: "-----" if x == "aaa" else x)
|
373 |
+
df.loc[idx, "test"] = temp
|
374 |
+
assert df.iloc[0, 2] == "-----"
|
375 |
+
|
376 |
+
def test_multitype_list_index_access(self):
|
377 |
+
# GH 10610
|
378 |
+
df = DataFrame(
|
379 |
+
np.random.default_rng(2).random((10, 5)), columns=["a"] + [20, 21, 22, 23]
|
380 |
+
)
|
381 |
+
|
382 |
+
with pytest.raises(KeyError, match=re.escape("'[26, -8] not in index'")):
|
383 |
+
df[[22, 26, -8]]
|
384 |
+
assert df[21].shape[0] == df.shape[0]
|
385 |
+
|
386 |
+
def test_set_index_nan(self):
|
387 |
+
# GH 3586
|
388 |
+
df = DataFrame(
|
389 |
+
{
|
390 |
+
"PRuid": {
|
391 |
+
17: "nonQC",
|
392 |
+
18: "nonQC",
|
393 |
+
19: "nonQC",
|
394 |
+
20: "10",
|
395 |
+
21: "11",
|
396 |
+
22: "12",
|
397 |
+
23: "13",
|
398 |
+
24: "24",
|
399 |
+
25: "35",
|
400 |
+
26: "46",
|
401 |
+
27: "47",
|
402 |
+
28: "48",
|
403 |
+
29: "59",
|
404 |
+
30: "10",
|
405 |
+
},
|
406 |
+
"QC": {
|
407 |
+
17: 0.0,
|
408 |
+
18: 0.0,
|
409 |
+
19: 0.0,
|
410 |
+
20: np.nan,
|
411 |
+
21: np.nan,
|
412 |
+
22: np.nan,
|
413 |
+
23: np.nan,
|
414 |
+
24: 1.0,
|
415 |
+
25: np.nan,
|
416 |
+
26: np.nan,
|
417 |
+
27: np.nan,
|
418 |
+
28: np.nan,
|
419 |
+
29: np.nan,
|
420 |
+
30: np.nan,
|
421 |
+
},
|
422 |
+
"data": {
|
423 |
+
17: 7.9544899999999998,
|
424 |
+
18: 8.0142609999999994,
|
425 |
+
19: 7.8591520000000008,
|
426 |
+
20: 0.86140349999999999,
|
427 |
+
21: 0.87853110000000001,
|
428 |
+
22: 0.8427041999999999,
|
429 |
+
23: 0.78587700000000005,
|
430 |
+
24: 0.73062459999999996,
|
431 |
+
25: 0.81668560000000001,
|
432 |
+
26: 0.81927080000000008,
|
433 |
+
27: 0.80705009999999999,
|
434 |
+
28: 0.81440240000000008,
|
435 |
+
29: 0.80140849999999997,
|
436 |
+
30: 0.81307740000000006,
|
437 |
+
},
|
438 |
+
"year": {
|
439 |
+
17: 2006,
|
440 |
+
18: 2007,
|
441 |
+
19: 2008,
|
442 |
+
20: 1985,
|
443 |
+
21: 1985,
|
444 |
+
22: 1985,
|
445 |
+
23: 1985,
|
446 |
+
24: 1985,
|
447 |
+
25: 1985,
|
448 |
+
26: 1985,
|
449 |
+
27: 1985,
|
450 |
+
28: 1985,
|
451 |
+
29: 1985,
|
452 |
+
30: 1986,
|
453 |
+
},
|
454 |
+
}
|
455 |
+
).reset_index()
|
456 |
+
|
457 |
+
result = (
|
458 |
+
df.set_index(["year", "PRuid", "QC"])
|
459 |
+
.reset_index()
|
460 |
+
.reindex(columns=df.columns)
|
461 |
+
)
|
462 |
+
tm.assert_frame_equal(result, df)
|
463 |
+
|
464 |
+
@pytest.mark.xfail(
|
465 |
+
using_pyarrow_string_dtype(), reason="can't multiply arrow strings"
|
466 |
+
)
|
467 |
+
def test_multi_assign(self):
|
468 |
+
# GH 3626, an assignment of a sub-df to a df
|
469 |
+
# set float64 to avoid upcast when setting nan
|
470 |
+
df = DataFrame(
|
471 |
+
{
|
472 |
+
"FC": ["a", "b", "a", "b", "a", "b"],
|
473 |
+
"PF": [0, 0, 0, 0, 1, 1],
|
474 |
+
"col1": list(range(6)),
|
475 |
+
"col2": list(range(6, 12)),
|
476 |
+
}
|
477 |
+
).astype({"col2": "float64"})
|
478 |
+
df.iloc[1, 0] = np.nan
|
479 |
+
df2 = df.copy()
|
480 |
+
|
481 |
+
mask = ~df2.FC.isna()
|
482 |
+
cols = ["col1", "col2"]
|
483 |
+
|
484 |
+
dft = df2 * 2
|
485 |
+
dft.iloc[3, 3] = np.nan
|
486 |
+
|
487 |
+
expected = DataFrame(
|
488 |
+
{
|
489 |
+
"FC": ["a", np.nan, "a", "b", "a", "b"],
|
490 |
+
"PF": [0, 0, 0, 0, 1, 1],
|
491 |
+
"col1": Series([0, 1, 4, 6, 8, 10]),
|
492 |
+
"col2": [12, 7, 16, np.nan, 20, 22],
|
493 |
+
}
|
494 |
+
)
|
495 |
+
|
496 |
+
# frame on rhs
|
497 |
+
df2.loc[mask, cols] = dft.loc[mask, cols]
|
498 |
+
tm.assert_frame_equal(df2, expected)
|
499 |
+
|
500 |
+
# with an ndarray on rhs
|
501 |
+
# coerces to float64 because values has float64 dtype
|
502 |
+
# GH 14001
|
503 |
+
expected = DataFrame(
|
504 |
+
{
|
505 |
+
"FC": ["a", np.nan, "a", "b", "a", "b"],
|
506 |
+
"PF": [0, 0, 0, 0, 1, 1],
|
507 |
+
"col1": [0, 1, 4, 6, 8, 10],
|
508 |
+
"col2": [12, 7, 16, np.nan, 20, 22],
|
509 |
+
}
|
510 |
+
)
|
511 |
+
df2 = df.copy()
|
512 |
+
df2.loc[mask, cols] = dft.loc[mask, cols].values
|
513 |
+
tm.assert_frame_equal(df2, expected)
|
514 |
+
|
515 |
+
def test_multi_assign_broadcasting_rhs(self):
|
516 |
+
# broadcasting on the rhs is required
|
517 |
+
df = DataFrame(
|
518 |
+
{
|
519 |
+
"A": [1, 2, 0, 0, 0],
|
520 |
+
"B": [0, 0, 0, 10, 11],
|
521 |
+
"C": [0, 0, 0, 10, 11],
|
522 |
+
"D": [3, 4, 5, 6, 7],
|
523 |
+
}
|
524 |
+
)
|
525 |
+
|
526 |
+
expected = df.copy()
|
527 |
+
mask = expected["A"] == 0
|
528 |
+
for col in ["A", "B"]:
|
529 |
+
expected.loc[mask, col] = df["D"]
|
530 |
+
|
531 |
+
df.loc[df["A"] == 0, ["A", "B"]] = df["D"].copy()
|
532 |
+
tm.assert_frame_equal(df, expected)
|
533 |
+
|
534 |
+
def test_setitem_list(self):
|
535 |
+
# GH 6043
|
536 |
+
# iloc with a list
|
537 |
+
df = DataFrame(index=[0, 1], columns=[0])
|
538 |
+
df.iloc[1, 0] = [1, 2, 3]
|
539 |
+
df.iloc[1, 0] = [1, 2]
|
540 |
+
|
541 |
+
result = DataFrame(index=[0, 1], columns=[0])
|
542 |
+
result.iloc[1, 0] = [1, 2]
|
543 |
+
|
544 |
+
tm.assert_frame_equal(result, df)
|
545 |
+
|
546 |
+
def test_string_slice(self):
|
547 |
+
# GH 14424
|
548 |
+
# string indexing against datetimelike with object
|
549 |
+
# dtype should properly raises KeyError
|
550 |
+
df = DataFrame([1], Index([pd.Timestamp("2011-01-01")], dtype=object))
|
551 |
+
assert df.index._is_all_dates
|
552 |
+
with pytest.raises(KeyError, match="'2011'"):
|
553 |
+
df["2011"]
|
554 |
+
|
555 |
+
with pytest.raises(KeyError, match="'2011'"):
|
556 |
+
df.loc["2011", 0]
|
557 |
+
|
558 |
+
def test_string_slice_empty(self):
|
559 |
+
# GH 14424
|
560 |
+
|
561 |
+
df = DataFrame()
|
562 |
+
assert not df.index._is_all_dates
|
563 |
+
with pytest.raises(KeyError, match="'2011'"):
|
564 |
+
df["2011"]
|
565 |
+
|
566 |
+
with pytest.raises(KeyError, match="^0$"):
|
567 |
+
df.loc["2011", 0]
|
568 |
+
|
569 |
+
def test_astype_assignment(self, using_infer_string):
|
570 |
+
# GH4312 (iloc)
|
571 |
+
df_orig = DataFrame(
|
572 |
+
[["1", "2", "3", ".4", 5, 6.0, "foo"]], columns=list("ABCDEFG")
|
573 |
+
)
|
574 |
+
|
575 |
+
df = df_orig.copy()
|
576 |
+
|
577 |
+
# with the enforcement of GH#45333 in 2.0, this setting is attempted inplace,
|
578 |
+
# so object dtype is retained
|
579 |
+
df.iloc[:, 0:2] = df.iloc[:, 0:2].astype(np.int64)
|
580 |
+
expected = DataFrame(
|
581 |
+
[[1, 2, "3", ".4", 5, 6.0, "foo"]], columns=list("ABCDEFG")
|
582 |
+
)
|
583 |
+
if not using_infer_string:
|
584 |
+
expected["A"] = expected["A"].astype(object)
|
585 |
+
expected["B"] = expected["B"].astype(object)
|
586 |
+
tm.assert_frame_equal(df, expected)
|
587 |
+
|
588 |
+
# GH5702 (loc)
|
589 |
+
df = df_orig.copy()
|
590 |
+
df.loc[:, "A"] = df.loc[:, "A"].astype(np.int64)
|
591 |
+
expected = DataFrame(
|
592 |
+
[[1, "2", "3", ".4", 5, 6.0, "foo"]], columns=list("ABCDEFG")
|
593 |
+
)
|
594 |
+
if not using_infer_string:
|
595 |
+
expected["A"] = expected["A"].astype(object)
|
596 |
+
tm.assert_frame_equal(df, expected)
|
597 |
+
|
598 |
+
df = df_orig.copy()
|
599 |
+
df.loc[:, ["B", "C"]] = df.loc[:, ["B", "C"]].astype(np.int64)
|
600 |
+
expected = DataFrame(
|
601 |
+
[["1", 2, 3, ".4", 5, 6.0, "foo"]], columns=list("ABCDEFG")
|
602 |
+
)
|
603 |
+
if not using_infer_string:
|
604 |
+
expected["B"] = expected["B"].astype(object)
|
605 |
+
expected["C"] = expected["C"].astype(object)
|
606 |
+
tm.assert_frame_equal(df, expected)
|
607 |
+
|
608 |
+
def test_astype_assignment_full_replacements(self):
|
609 |
+
# full replacements / no nans
|
610 |
+
df = DataFrame({"A": [1.0, 2.0, 3.0, 4.0]})
|
611 |
+
|
612 |
+
# With the enforcement of GH#45333 in 2.0, this assignment occurs inplace,
|
613 |
+
# so float64 is retained
|
614 |
+
df.iloc[:, 0] = df["A"].astype(np.int64)
|
615 |
+
expected = DataFrame({"A": [1.0, 2.0, 3.0, 4.0]})
|
616 |
+
tm.assert_frame_equal(df, expected)
|
617 |
+
|
618 |
+
df = DataFrame({"A": [1.0, 2.0, 3.0, 4.0]})
|
619 |
+
df.loc[:, "A"] = df["A"].astype(np.int64)
|
620 |
+
tm.assert_frame_equal(df, expected)
|
621 |
+
|
622 |
+
@pytest.mark.parametrize("indexer", [tm.getitem, tm.loc])
|
623 |
+
def test_index_type_coercion(self, indexer):
|
624 |
+
# GH 11836
|
625 |
+
# if we have an index type and set it with something that looks
|
626 |
+
# to numpy like the same, but is actually, not
|
627 |
+
# (e.g. setting with a float or string '0')
|
628 |
+
# then we need to coerce to object
|
629 |
+
|
630 |
+
# integer indexes
|
631 |
+
for s in [Series(range(5)), Series(range(5), index=range(1, 6))]:
|
632 |
+
assert is_integer_dtype(s.index)
|
633 |
+
|
634 |
+
s2 = s.copy()
|
635 |
+
indexer(s2)[0.1] = 0
|
636 |
+
assert is_float_dtype(s2.index)
|
637 |
+
assert indexer(s2)[0.1] == 0
|
638 |
+
|
639 |
+
s2 = s.copy()
|
640 |
+
indexer(s2)[0.0] = 0
|
641 |
+
exp = s.index
|
642 |
+
if 0 not in s:
|
643 |
+
exp = Index(s.index.tolist() + [0])
|
644 |
+
tm.assert_index_equal(s2.index, exp)
|
645 |
+
|
646 |
+
s2 = s.copy()
|
647 |
+
indexer(s2)["0"] = 0
|
648 |
+
assert is_object_dtype(s2.index)
|
649 |
+
|
650 |
+
for s in [Series(range(5), index=np.arange(5.0))]:
|
651 |
+
assert is_float_dtype(s.index)
|
652 |
+
|
653 |
+
s2 = s.copy()
|
654 |
+
indexer(s2)[0.1] = 0
|
655 |
+
assert is_float_dtype(s2.index)
|
656 |
+
assert indexer(s2)[0.1] == 0
|
657 |
+
|
658 |
+
s2 = s.copy()
|
659 |
+
indexer(s2)[0.0] = 0
|
660 |
+
tm.assert_index_equal(s2.index, s.index)
|
661 |
+
|
662 |
+
s2 = s.copy()
|
663 |
+
indexer(s2)["0"] = 0
|
664 |
+
assert is_object_dtype(s2.index)
|
665 |
+
|
666 |
+
|
667 |
+
class TestMisc:
|
668 |
+
def test_float_index_to_mixed(self):
|
669 |
+
df = DataFrame(
|
670 |
+
{
|
671 |
+
0.0: np.random.default_rng(2).random(10),
|
672 |
+
1.0: np.random.default_rng(2).random(10),
|
673 |
+
}
|
674 |
+
)
|
675 |
+
df["a"] = 10
|
676 |
+
|
677 |
+
expected = DataFrame({0.0: df[0.0], 1.0: df[1.0], "a": [10] * 10})
|
678 |
+
tm.assert_frame_equal(expected, df)
|
679 |
+
|
680 |
+
def test_float_index_non_scalar_assignment(self):
|
681 |
+
df = DataFrame({"a": [1, 2, 3], "b": [3, 4, 5]}, index=[1.0, 2.0, 3.0])
|
682 |
+
df.loc[df.index[:2]] = 1
|
683 |
+
expected = DataFrame({"a": [1, 1, 3], "b": [1, 1, 5]}, index=df.index)
|
684 |
+
tm.assert_frame_equal(expected, df)
|
685 |
+
|
686 |
+
def test_loc_setitem_fullindex_views(self):
|
687 |
+
df = DataFrame({"a": [1, 2, 3], "b": [3, 4, 5]}, index=[1.0, 2.0, 3.0])
|
688 |
+
df2 = df.copy()
|
689 |
+
df.loc[df.index] = df.loc[df.index]
|
690 |
+
tm.assert_frame_equal(df, df2)
|
691 |
+
|
692 |
+
@pytest.mark.xfail(using_pyarrow_string_dtype(), reason="can't set int into string")
|
693 |
+
def test_rhs_alignment(self):
|
694 |
+
# GH8258, tests that both rows & columns are aligned to what is
|
695 |
+
# assigned to. covers both uniform data-type & multi-type cases
|
696 |
+
def run_tests(df, rhs, right_loc, right_iloc):
|
697 |
+
# label, index, slice
|
698 |
+
lbl_one, idx_one, slice_one = list("bcd"), [1, 2, 3], slice(1, 4)
|
699 |
+
lbl_two, idx_two, slice_two = ["joe", "jolie"], [1, 2], slice(1, 3)
|
700 |
+
|
701 |
+
left = df.copy()
|
702 |
+
left.loc[lbl_one, lbl_two] = rhs
|
703 |
+
tm.assert_frame_equal(left, right_loc)
|
704 |
+
|
705 |
+
left = df.copy()
|
706 |
+
left.iloc[idx_one, idx_two] = rhs
|
707 |
+
tm.assert_frame_equal(left, right_iloc)
|
708 |
+
|
709 |
+
left = df.copy()
|
710 |
+
left.iloc[slice_one, slice_two] = rhs
|
711 |
+
tm.assert_frame_equal(left, right_iloc)
|
712 |
+
|
713 |
+
xs = np.arange(20).reshape(5, 4)
|
714 |
+
cols = ["jim", "joe", "jolie", "joline"]
|
715 |
+
df = DataFrame(xs, columns=cols, index=list("abcde"), dtype="int64")
|
716 |
+
|
717 |
+
# right hand side; permute the indices and multiplpy by -2
|
718 |
+
rhs = -2 * df.iloc[3:0:-1, 2:0:-1]
|
719 |
+
|
720 |
+
# expected `right` result; just multiply by -2
|
721 |
+
right_iloc = df.copy()
|
722 |
+
right_iloc["joe"] = [1, 14, 10, 6, 17]
|
723 |
+
right_iloc["jolie"] = [2, 13, 9, 5, 18]
|
724 |
+
right_iloc.iloc[1:4, 1:3] *= -2
|
725 |
+
right_loc = df.copy()
|
726 |
+
right_loc.iloc[1:4, 1:3] *= -2
|
727 |
+
|
728 |
+
# run tests with uniform dtypes
|
729 |
+
run_tests(df, rhs, right_loc, right_iloc)
|
730 |
+
|
731 |
+
# make frames multi-type & re-run tests
|
732 |
+
for frame in [df, rhs, right_loc, right_iloc]:
|
733 |
+
frame["joe"] = frame["joe"].astype("float64")
|
734 |
+
frame["jolie"] = frame["jolie"].map(lambda x: f"@{x}")
|
735 |
+
right_iloc["joe"] = [1.0, "@-28", "@-20", "@-12", 17.0]
|
736 |
+
right_iloc["jolie"] = ["@2", -26.0, -18.0, -10.0, "@18"]
|
737 |
+
with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):
|
738 |
+
run_tests(df, rhs, right_loc, right_iloc)
|
739 |
+
|
740 |
+
@pytest.mark.parametrize(
|
741 |
+
"idx", [_mklbl("A", 20), np.arange(20) + 100, np.linspace(100, 150, 20)]
|
742 |
+
)
|
743 |
+
def test_str_label_slicing_with_negative_step(self, idx):
|
744 |
+
SLC = pd.IndexSlice
|
745 |
+
|
746 |
+
idx = Index(idx)
|
747 |
+
ser = Series(np.arange(20), index=idx)
|
748 |
+
tm.assert_indexing_slices_equivalent(ser, SLC[idx[9] :: -1], SLC[9::-1])
|
749 |
+
tm.assert_indexing_slices_equivalent(ser, SLC[: idx[9] : -1], SLC[:8:-1])
|
750 |
+
tm.assert_indexing_slices_equivalent(
|
751 |
+
ser, SLC[idx[13] : idx[9] : -1], SLC[13:8:-1]
|
752 |
+
)
|
753 |
+
tm.assert_indexing_slices_equivalent(ser, SLC[idx[9] : idx[13] : -1], SLC[:0])
|
754 |
+
|
755 |
+
def test_slice_with_zero_step_raises(self, index, indexer_sl, frame_or_series):
|
756 |
+
obj = frame_or_series(np.arange(len(index)), index=index)
|
757 |
+
with pytest.raises(ValueError, match="slice step cannot be zero"):
|
758 |
+
indexer_sl(obj)[::0]
|
759 |
+
|
760 |
+
def test_loc_setitem_indexing_assignment_dict_already_exists(self):
|
761 |
+
index = Index([-5, 0, 5], name="z")
|
762 |
+
df = DataFrame({"x": [1, 2, 6], "y": [2, 2, 8]}, index=index)
|
763 |
+
expected = df.copy()
|
764 |
+
rhs = {"x": 9, "y": 99}
|
765 |
+
df.loc[5] = rhs
|
766 |
+
expected.loc[5] = [9, 99]
|
767 |
+
tm.assert_frame_equal(df, expected)
|
768 |
+
|
769 |
+
# GH#38335 same thing, mixed dtypes
|
770 |
+
df = DataFrame({"x": [1, 2, 6], "y": [2.0, 2.0, 8.0]}, index=index)
|
771 |
+
df.loc[5] = rhs
|
772 |
+
expected = DataFrame({"x": [1, 2, 9], "y": [2.0, 2.0, 99.0]}, index=index)
|
773 |
+
tm.assert_frame_equal(df, expected)
|
774 |
+
|
775 |
+
def test_iloc_getitem_indexing_dtypes_on_empty(self):
|
776 |
+
# Check that .iloc returns correct dtypes GH9983
|
777 |
+
df = DataFrame({"a": [1, 2, 3], "b": ["b", "b2", "b3"]})
|
778 |
+
df2 = df.iloc[[], :]
|
779 |
+
|
780 |
+
assert df2.loc[:, "a"].dtype == np.int64
|
781 |
+
tm.assert_series_equal(df2.loc[:, "a"], df2.iloc[:, 0])
|
782 |
+
|
783 |
+
@pytest.mark.parametrize("size", [5, 999999, 1000000])
|
784 |
+
def test_loc_range_in_series_indexing(self, size):
|
785 |
+
# range can cause an indexing error
|
786 |
+
# GH 11652
|
787 |
+
s = Series(index=range(size), dtype=np.float64)
|
788 |
+
s.loc[range(1)] = 42
|
789 |
+
tm.assert_series_equal(s.loc[range(1)], Series(42.0, index=[0]))
|
790 |
+
|
791 |
+
s.loc[range(2)] = 43
|
792 |
+
tm.assert_series_equal(s.loc[range(2)], Series(43.0, index=[0, 1]))
|
793 |
+
|
794 |
+
def test_partial_boolean_frame_indexing(self):
|
795 |
+
# GH 17170
|
796 |
+
df = DataFrame(
|
797 |
+
np.arange(9.0).reshape(3, 3), index=list("abc"), columns=list("ABC")
|
798 |
+
)
|
799 |
+
index_df = DataFrame(1, index=list("ab"), columns=list("AB"))
|
800 |
+
result = df[index_df.notnull()]
|
801 |
+
expected = DataFrame(
|
802 |
+
np.array([[0.0, 1.0, np.nan], [3.0, 4.0, np.nan], [np.nan] * 3]),
|
803 |
+
index=list("abc"),
|
804 |
+
columns=list("ABC"),
|
805 |
+
)
|
806 |
+
tm.assert_frame_equal(result, expected)
|
807 |
+
|
808 |
+
def test_no_reference_cycle(self):
|
809 |
+
df = DataFrame({"a": [0, 1], "b": [2, 3]})
|
810 |
+
for name in ("loc", "iloc", "at", "iat"):
|
811 |
+
getattr(df, name)
|
812 |
+
wr = weakref.ref(df)
|
813 |
+
del df
|
814 |
+
assert wr() is None
|
815 |
+
|
816 |
+
def test_label_indexing_on_nan(self, nulls_fixture):
|
817 |
+
# GH 32431
|
818 |
+
df = Series([1, "{1,2}", 1, nulls_fixture])
|
819 |
+
vc = df.value_counts(dropna=False)
|
820 |
+
result1 = vc.loc[nulls_fixture]
|
821 |
+
result2 = vc[nulls_fixture]
|
822 |
+
|
823 |
+
expected = 1
|
824 |
+
assert result1 == expected
|
825 |
+
assert result2 == expected
|
826 |
+
|
827 |
+
|
828 |
+
class TestDataframeNoneCoercion:
|
829 |
+
EXPECTED_SINGLE_ROW_RESULTS = [
|
830 |
+
# For numeric series, we should coerce to NaN.
|
831 |
+
([1, 2, 3], [np.nan, 2, 3], FutureWarning),
|
832 |
+
([1.0, 2.0, 3.0], [np.nan, 2.0, 3.0], None),
|
833 |
+
# For datetime series, we should coerce to NaT.
|
834 |
+
(
|
835 |
+
[datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)],
|
836 |
+
[NaT, datetime(2000, 1, 2), datetime(2000, 1, 3)],
|
837 |
+
None,
|
838 |
+
),
|
839 |
+
# For objects, we should preserve the None value.
|
840 |
+
(["foo", "bar", "baz"], [None, "bar", "baz"], None),
|
841 |
+
]
|
842 |
+
|
843 |
+
@pytest.mark.parametrize("expected", EXPECTED_SINGLE_ROW_RESULTS)
|
844 |
+
def test_coercion_with_loc(self, expected):
|
845 |
+
start_data, expected_result, warn = expected
|
846 |
+
|
847 |
+
start_dataframe = DataFrame({"foo": start_data})
|
848 |
+
start_dataframe.loc[0, ["foo"]] = None
|
849 |
+
|
850 |
+
expected_dataframe = DataFrame({"foo": expected_result})
|
851 |
+
tm.assert_frame_equal(start_dataframe, expected_dataframe)
|
852 |
+
|
853 |
+
@pytest.mark.parametrize("expected", EXPECTED_SINGLE_ROW_RESULTS)
|
854 |
+
def test_coercion_with_setitem_and_dataframe(self, expected):
|
855 |
+
start_data, expected_result, warn = expected
|
856 |
+
|
857 |
+
start_dataframe = DataFrame({"foo": start_data})
|
858 |
+
start_dataframe[start_dataframe["foo"] == start_dataframe["foo"][0]] = None
|
859 |
+
|
860 |
+
expected_dataframe = DataFrame({"foo": expected_result})
|
861 |
+
tm.assert_frame_equal(start_dataframe, expected_dataframe)
|
862 |
+
|
863 |
+
@pytest.mark.parametrize("expected", EXPECTED_SINGLE_ROW_RESULTS)
|
864 |
+
def test_none_coercion_loc_and_dataframe(self, expected):
|
865 |
+
start_data, expected_result, warn = expected
|
866 |
+
|
867 |
+
start_dataframe = DataFrame({"foo": start_data})
|
868 |
+
start_dataframe.loc[start_dataframe["foo"] == start_dataframe["foo"][0]] = None
|
869 |
+
|
870 |
+
expected_dataframe = DataFrame({"foo": expected_result})
|
871 |
+
tm.assert_frame_equal(start_dataframe, expected_dataframe)
|
872 |
+
|
873 |
+
def test_none_coercion_mixed_dtypes(self):
|
874 |
+
start_dataframe = DataFrame(
|
875 |
+
{
|
876 |
+
"a": [1, 2, 3],
|
877 |
+
"b": [1.0, 2.0, 3.0],
|
878 |
+
"c": [datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)],
|
879 |
+
"d": ["a", "b", "c"],
|
880 |
+
}
|
881 |
+
)
|
882 |
+
start_dataframe.iloc[0] = None
|
883 |
+
|
884 |
+
exp = DataFrame(
|
885 |
+
{
|
886 |
+
"a": [np.nan, 2, 3],
|
887 |
+
"b": [np.nan, 2.0, 3.0],
|
888 |
+
"c": [NaT, datetime(2000, 1, 2), datetime(2000, 1, 3)],
|
889 |
+
"d": [None, "b", "c"],
|
890 |
+
}
|
891 |
+
)
|
892 |
+
tm.assert_frame_equal(start_dataframe, exp)
|
893 |
+
|
894 |
+
|
895 |
+
class TestDatetimelikeCoercion:
|
896 |
+
def test_setitem_dt64_string_scalar(self, tz_naive_fixture, indexer_sli):
|
897 |
+
# dispatching _can_hold_element to underlying DatetimeArray
|
898 |
+
tz = tz_naive_fixture
|
899 |
+
|
900 |
+
dti = date_range("2016-01-01", periods=3, tz=tz)
|
901 |
+
ser = Series(dti.copy(deep=True))
|
902 |
+
|
903 |
+
values = ser._values
|
904 |
+
|
905 |
+
newval = "2018-01-01"
|
906 |
+
values._validate_setitem_value(newval)
|
907 |
+
|
908 |
+
indexer_sli(ser)[0] = newval
|
909 |
+
|
910 |
+
if tz is None:
|
911 |
+
# TODO(EA2D): we can make this no-copy in tz-naive case too
|
912 |
+
assert ser.dtype == dti.dtype
|
913 |
+
assert ser._values._ndarray is values._ndarray
|
914 |
+
else:
|
915 |
+
assert ser._values is values
|
916 |
+
|
917 |
+
@pytest.mark.parametrize("box", [list, np.array, pd.array, pd.Categorical, Index])
|
918 |
+
@pytest.mark.parametrize(
|
919 |
+
"key", [[0, 1], slice(0, 2), np.array([True, True, False])]
|
920 |
+
)
|
921 |
+
def test_setitem_dt64_string_values(self, tz_naive_fixture, indexer_sli, key, box):
|
922 |
+
# dispatching _can_hold_element to underling DatetimeArray
|
923 |
+
tz = tz_naive_fixture
|
924 |
+
|
925 |
+
if isinstance(key, slice) and indexer_sli is tm.loc:
|
926 |
+
key = slice(0, 1)
|
927 |
+
|
928 |
+
dti = date_range("2016-01-01", periods=3, tz=tz)
|
929 |
+
ser = Series(dti.copy(deep=True))
|
930 |
+
|
931 |
+
values = ser._values
|
932 |
+
|
933 |
+
newvals = box(["2019-01-01", "2010-01-02"])
|
934 |
+
values._validate_setitem_value(newvals)
|
935 |
+
|
936 |
+
indexer_sli(ser)[key] = newvals
|
937 |
+
|
938 |
+
if tz is None:
|
939 |
+
# TODO(EA2D): we can make this no-copy in tz-naive case too
|
940 |
+
assert ser.dtype == dti.dtype
|
941 |
+
assert ser._values._ndarray is values._ndarray
|
942 |
+
else:
|
943 |
+
assert ser._values is values
|
944 |
+
|
945 |
+
@pytest.mark.parametrize("scalar", ["3 Days", offsets.Hour(4)])
|
946 |
+
def test_setitem_td64_scalar(self, indexer_sli, scalar):
|
947 |
+
# dispatching _can_hold_element to underling TimedeltaArray
|
948 |
+
tdi = timedelta_range("1 Day", periods=3)
|
949 |
+
ser = Series(tdi.copy(deep=True))
|
950 |
+
|
951 |
+
values = ser._values
|
952 |
+
values._validate_setitem_value(scalar)
|
953 |
+
|
954 |
+
indexer_sli(ser)[0] = scalar
|
955 |
+
assert ser._values._ndarray is values._ndarray
|
956 |
+
|
957 |
+
@pytest.mark.parametrize("box", [list, np.array, pd.array, pd.Categorical, Index])
|
958 |
+
@pytest.mark.parametrize(
|
959 |
+
"key", [[0, 1], slice(0, 2), np.array([True, True, False])]
|
960 |
+
)
|
961 |
+
def test_setitem_td64_string_values(self, indexer_sli, key, box):
|
962 |
+
# dispatching _can_hold_element to underling TimedeltaArray
|
963 |
+
if isinstance(key, slice) and indexer_sli is tm.loc:
|
964 |
+
key = slice(0, 1)
|
965 |
+
|
966 |
+
tdi = timedelta_range("1 Day", periods=3)
|
967 |
+
ser = Series(tdi.copy(deep=True))
|
968 |
+
|
969 |
+
values = ser._values
|
970 |
+
|
971 |
+
newvals = box(["10 Days", "44 hours"])
|
972 |
+
values._validate_setitem_value(newvals)
|
973 |
+
|
974 |
+
indexer_sli(ser)[key] = newvals
|
975 |
+
assert ser._values._ndarray is values._ndarray
|
976 |
+
|
977 |
+
|
978 |
+
def test_extension_array_cross_section():
|
979 |
+
# A cross-section of a homogeneous EA should be an EA
|
980 |
+
df = DataFrame(
|
981 |
+
{
|
982 |
+
"A": pd.array([1, 2], dtype="Int64"),
|
983 |
+
"B": pd.array([3, 4], dtype="Int64"),
|
984 |
+
},
|
985 |
+
index=["a", "b"],
|
986 |
+
)
|
987 |
+
expected = Series(pd.array([1, 3], dtype="Int64"), index=["A", "B"], name="a")
|
988 |
+
result = df.loc["a"]
|
989 |
+
tm.assert_series_equal(result, expected)
|
990 |
+
|
991 |
+
result = df.iloc[0]
|
992 |
+
tm.assert_series_equal(result, expected)
|
993 |
+
|
994 |
+
|
995 |
+
def test_extension_array_cross_section_converts():
|
996 |
+
# all numeric columns -> numeric series
|
997 |
+
df = DataFrame(
|
998 |
+
{
|
999 |
+
"A": pd.array([1, 2], dtype="Int64"),
|
1000 |
+
"B": np.array([1, 2], dtype="int64"),
|
1001 |
+
},
|
1002 |
+
index=["a", "b"],
|
1003 |
+
)
|
1004 |
+
result = df.loc["a"]
|
1005 |
+
expected = Series([1, 1], dtype="Int64", index=["A", "B"], name="a")
|
1006 |
+
tm.assert_series_equal(result, expected)
|
1007 |
+
|
1008 |
+
result = df.iloc[0]
|
1009 |
+
tm.assert_series_equal(result, expected)
|
1010 |
+
|
1011 |
+
# mixed columns -> object series
|
1012 |
+
df = DataFrame(
|
1013 |
+
{"A": pd.array([1, 2], dtype="Int64"), "B": np.array(["a", "b"])},
|
1014 |
+
index=["a", "b"],
|
1015 |
+
)
|
1016 |
+
result = df.loc["a"]
|
1017 |
+
expected = Series([1, "a"], dtype=object, index=["A", "B"], name="a")
|
1018 |
+
tm.assert_series_equal(result, expected)
|
1019 |
+
|
1020 |
+
result = df.iloc[0]
|
1021 |
+
tm.assert_series_equal(result, expected)
|
1022 |
+
|
1023 |
+
|
1024 |
+
@pytest.mark.parametrize(
|
1025 |
+
"ser, keys",
|
1026 |
+
[(Series([10]), (0, 0)), (Series([1, 2, 3], index=list("abc")), (0, 1))],
|
1027 |
+
)
|
1028 |
+
def test_ser_tup_indexer_exceeds_dimensions(ser, keys, indexer_li):
|
1029 |
+
# GH#13831
|
1030 |
+
exp_err, exp_msg = IndexingError, "Too many indexers"
|
1031 |
+
with pytest.raises(exp_err, match=exp_msg):
|
1032 |
+
indexer_li(ser)[keys]
|
1033 |
+
|
1034 |
+
if indexer_li == tm.iloc:
|
1035 |
+
# For iloc.__setitem__ we let numpy handle the error reporting.
|
1036 |
+
exp_err, exp_msg = IndexError, "too many indices for array"
|
1037 |
+
|
1038 |
+
with pytest.raises(exp_err, match=exp_msg):
|
1039 |
+
indexer_li(ser)[keys] = 0
|
1040 |
+
|
1041 |
+
|
1042 |
+
def test_ser_list_indexer_exceeds_dimensions(indexer_li):
|
1043 |
+
# GH#13831
|
1044 |
+
# Make sure an exception is raised when a tuple exceeds the dimension of the series,
|
1045 |
+
# but not list when a list is used.
|
1046 |
+
ser = Series([10])
|
1047 |
+
res = indexer_li(ser)[[0, 0]]
|
1048 |
+
exp = Series([10, 10], index=Index([0, 0]))
|
1049 |
+
tm.assert_series_equal(res, exp)
|
1050 |
+
|
1051 |
+
|
1052 |
+
@pytest.mark.parametrize(
|
1053 |
+
"value", [(0, 1), [0, 1], np.array([0, 1]), array.array("b", [0, 1])]
|
1054 |
+
)
|
1055 |
+
def test_scalar_setitem_with_nested_value(value):
|
1056 |
+
# For numeric data, we try to unpack and thus raise for mismatching length
|
1057 |
+
df = DataFrame({"A": [1, 2, 3]})
|
1058 |
+
msg = "|".join(
|
1059 |
+
[
|
1060 |
+
"Must have equal len keys and value",
|
1061 |
+
"setting an array element with a sequence",
|
1062 |
+
]
|
1063 |
+
)
|
1064 |
+
with pytest.raises(ValueError, match=msg):
|
1065 |
+
df.loc[0, "B"] = value
|
1066 |
+
|
1067 |
+
# TODO For object dtype this happens as well, but should we rather preserve
|
1068 |
+
# the nested data and set as such?
|
1069 |
+
df = DataFrame({"A": [1, 2, 3], "B": np.array([1, "a", "b"], dtype=object)})
|
1070 |
+
with pytest.raises(ValueError, match="Must have equal len keys and value"):
|
1071 |
+
df.loc[0, "B"] = value
|
1072 |
+
# if isinstance(value, np.ndarray):
|
1073 |
+
# assert (df.loc[0, "B"] == value).all()
|
1074 |
+
# else:
|
1075 |
+
# assert df.loc[0, "B"] == value
|
1076 |
+
|
1077 |
+
|
1078 |
+
@pytest.mark.parametrize(
|
1079 |
+
"value", [(0, 1), [0, 1], np.array([0, 1]), array.array("b", [0, 1])]
|
1080 |
+
)
|
1081 |
+
def test_scalar_setitem_series_with_nested_value(value, indexer_sli):
|
1082 |
+
# For numeric data, we try to unpack and thus raise for mismatching length
|
1083 |
+
ser = Series([1, 2, 3])
|
1084 |
+
with pytest.raises(ValueError, match="setting an array element with a sequence"):
|
1085 |
+
indexer_sli(ser)[0] = value
|
1086 |
+
|
1087 |
+
# but for object dtype we preserve the nested data and set as such
|
1088 |
+
ser = Series([1, "a", "b"], dtype=object)
|
1089 |
+
indexer_sli(ser)[0] = value
|
1090 |
+
if isinstance(value, np.ndarray):
|
1091 |
+
assert (ser.loc[0] == value).all()
|
1092 |
+
else:
|
1093 |
+
assert ser.loc[0] == value
|
1094 |
+
|
1095 |
+
|
1096 |
+
@pytest.mark.parametrize(
|
1097 |
+
"value", [(0.0,), [0.0], np.array([0.0]), array.array("d", [0.0])]
|
1098 |
+
)
|
1099 |
+
def test_scalar_setitem_with_nested_value_length1(value):
|
1100 |
+
# https://github.com/pandas-dev/pandas/issues/46268
|
1101 |
+
|
1102 |
+
# For numeric data, assigning length-1 array to scalar position gets unpacked
|
1103 |
+
df = DataFrame({"A": [1, 2, 3]})
|
1104 |
+
df.loc[0, "B"] = value
|
1105 |
+
expected = DataFrame({"A": [1, 2, 3], "B": [0.0, np.nan, np.nan]})
|
1106 |
+
tm.assert_frame_equal(df, expected)
|
1107 |
+
|
1108 |
+
# but for object dtype we preserve the nested data
|
1109 |
+
df = DataFrame({"A": [1, 2, 3], "B": np.array([1, "a", "b"], dtype=object)})
|
1110 |
+
df.loc[0, "B"] = value
|
1111 |
+
if isinstance(value, np.ndarray):
|
1112 |
+
assert (df.loc[0, "B"] == value).all()
|
1113 |
+
else:
|
1114 |
+
assert df.loc[0, "B"] == value
|
1115 |
+
|
1116 |
+
|
1117 |
+
@pytest.mark.parametrize(
|
1118 |
+
"value", [(0.0,), [0.0], np.array([0.0]), array.array("d", [0.0])]
|
1119 |
+
)
|
1120 |
+
def test_scalar_setitem_series_with_nested_value_length1(value, indexer_sli):
|
1121 |
+
# For numeric data, assigning length-1 array to scalar position gets unpacked
|
1122 |
+
# TODO this only happens in case of ndarray, should we make this consistent
|
1123 |
+
# for all list-likes? (as happens for DataFrame.(i)loc, see test above)
|
1124 |
+
ser = Series([1.0, 2.0, 3.0])
|
1125 |
+
if isinstance(value, np.ndarray):
|
1126 |
+
indexer_sli(ser)[0] = value
|
1127 |
+
expected = Series([0.0, 2.0, 3.0])
|
1128 |
+
tm.assert_series_equal(ser, expected)
|
1129 |
+
else:
|
1130 |
+
with pytest.raises(
|
1131 |
+
ValueError, match="setting an array element with a sequence"
|
1132 |
+
):
|
1133 |
+
indexer_sli(ser)[0] = value
|
1134 |
+
|
1135 |
+
# but for object dtype we preserve the nested data
|
1136 |
+
ser = Series([1, "a", "b"], dtype=object)
|
1137 |
+
indexer_sli(ser)[0] = value
|
1138 |
+
if isinstance(value, np.ndarray):
|
1139 |
+
assert (ser.loc[0] == value).all()
|
1140 |
+
else:
|
1141 |
+
assert ser.loc[0] == value
|
1142 |
+
|
1143 |
+
|
1144 |
+
def test_object_dtype_series_set_series_element():
|
1145 |
+
# GH 48933
|
1146 |
+
s1 = Series(dtype="O", index=["a", "b"])
|
1147 |
+
|
1148 |
+
s1["a"] = Series()
|
1149 |
+
s1.loc["b"] = Series()
|
1150 |
+
|
1151 |
+
tm.assert_series_equal(s1.loc["a"], Series())
|
1152 |
+
tm.assert_series_equal(s1.loc["b"], Series())
|
1153 |
+
|
1154 |
+
s2 = Series(dtype="O", index=["a", "b"])
|
1155 |
+
|
1156 |
+
s2.iloc[1] = Series()
|
1157 |
+
tm.assert_series_equal(s2.iloc[1], Series())
|