Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- llmeval-env/lib/python3.10/site-packages/pandas/tests/arrays/interval/__pycache__/test_astype.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/arrays/interval/__pycache__/test_interval_pyarrow.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/arrays/interval/__pycache__/test_overlaps.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/arrays/masked/test_function.py +74 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/common.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/conftest.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_categorical.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_datetime.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_floats.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_iat.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_iloc.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_indexers.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_indexing.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_partial.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_scalar.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/interval/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/interval/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/interval/__pycache__/test_interval.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/interval/__pycache__/test_interval_new.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/interval/test_interval.py +227 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/interval/test_interval_new.py +232 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_chaining_and_caching.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_datetime.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_getitem.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_iloc.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_indexing_slow.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_loc.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_multiindex.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_partial.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_setitem.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_slice.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_sorted.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_chaining_and_caching.py +87 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_datetime.py +50 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_getitem.py +410 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_iloc.py +171 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_indexing_slow.py +118 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_loc.py +992 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_multiindex.py +235 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_partial.py +269 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_setitem.py +589 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_slice.py +796 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_sorted.py +153 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/tslibs/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_ccalendar.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_conversion.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_fields.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_npy_units.cpython-310.pyc +0 -0
llmeval-env/lib/python3.10/site-packages/pandas/tests/arrays/interval/__pycache__/test_astype.cpython-310.pyc
ADDED
Binary file (1.07 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/arrays/interval/__pycache__/test_interval_pyarrow.cpython-310.pyc
ADDED
Binary file (4.42 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/arrays/interval/__pycache__/test_overlaps.cpython-310.pyc
ADDED
Binary file (3.42 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/arrays/masked/test_function.py
ADDED
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas.core.dtypes.common import is_integer_dtype
|
5 |
+
|
6 |
+
import pandas as pd
|
7 |
+
import pandas._testing as tm
|
8 |
+
from pandas.core.arrays import BaseMaskedArray
|
9 |
+
|
10 |
+
arrays = [pd.array([1, 2, 3, None], dtype=dtype) for dtype in tm.ALL_INT_EA_DTYPES]
|
11 |
+
arrays += [
|
12 |
+
pd.array([0.141, -0.268, 5.895, None], dtype=dtype) for dtype in tm.FLOAT_EA_DTYPES
|
13 |
+
]
|
14 |
+
|
15 |
+
|
16 |
+
@pytest.fixture(params=arrays, ids=[a.dtype.name for a in arrays])
|
17 |
+
def data(request):
|
18 |
+
"""
|
19 |
+
Fixture returning parametrized 'data' array with different integer and
|
20 |
+
floating point types
|
21 |
+
"""
|
22 |
+
return request.param
|
23 |
+
|
24 |
+
|
25 |
+
@pytest.fixture()
|
26 |
+
def numpy_dtype(data):
|
27 |
+
"""
|
28 |
+
Fixture returning numpy dtype from 'data' input array.
|
29 |
+
"""
|
30 |
+
# For integer dtype, the numpy conversion must be done to float
|
31 |
+
if is_integer_dtype(data):
|
32 |
+
numpy_dtype = float
|
33 |
+
else:
|
34 |
+
numpy_dtype = data.dtype.type
|
35 |
+
return numpy_dtype
|
36 |
+
|
37 |
+
|
38 |
+
def test_round(data, numpy_dtype):
|
39 |
+
# No arguments
|
40 |
+
result = data.round()
|
41 |
+
expected = pd.array(
|
42 |
+
np.round(data.to_numpy(dtype=numpy_dtype, na_value=None)), dtype=data.dtype
|
43 |
+
)
|
44 |
+
tm.assert_extension_array_equal(result, expected)
|
45 |
+
|
46 |
+
# Decimals argument
|
47 |
+
result = data.round(decimals=2)
|
48 |
+
expected = pd.array(
|
49 |
+
np.round(data.to_numpy(dtype=numpy_dtype, na_value=None), decimals=2),
|
50 |
+
dtype=data.dtype,
|
51 |
+
)
|
52 |
+
tm.assert_extension_array_equal(result, expected)
|
53 |
+
|
54 |
+
|
55 |
+
def test_tolist(data):
|
56 |
+
result = data.tolist()
|
57 |
+
expected = list(data)
|
58 |
+
tm.assert_equal(result, expected)
|
59 |
+
|
60 |
+
|
61 |
+
def test_to_numpy():
|
62 |
+
# GH#56991
|
63 |
+
|
64 |
+
class MyStringArray(BaseMaskedArray):
|
65 |
+
dtype = pd.StringDtype()
|
66 |
+
_dtype_cls = pd.StringDtype
|
67 |
+
_internal_fill_value = pd.NA
|
68 |
+
|
69 |
+
arr = MyStringArray(
|
70 |
+
values=np.array(["a", "b", "c"]), mask=np.array([False, True, False])
|
71 |
+
)
|
72 |
+
result = arr.to_numpy()
|
73 |
+
expected = np.array(["a", pd.NA, "c"])
|
74 |
+
tm.assert_numpy_array_equal(result, expected)
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/common.cpython-310.pyc
ADDED
Binary file (1.3 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/conftest.cpython-310.pyc
ADDED
Binary file (3.55 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_categorical.cpython-310.pyc
ADDED
Binary file (15.4 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_datetime.cpython-310.pyc
ADDED
Binary file (5.41 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_floats.cpython-310.pyc
ADDED
Binary file (14.9 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_iat.cpython-310.pyc
ADDED
Binary file (1.73 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_iloc.cpython-310.pyc
ADDED
Binary file (44.7 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_indexers.cpython-310.pyc
ADDED
Binary file (2.35 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_indexing.cpython-310.pyc
ADDED
Binary file (31.9 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_partial.cpython-310.pyc
ADDED
Binary file (19.3 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_scalar.cpython-310.pyc
ADDED
Binary file (9.76 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/interval/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/interval/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (203 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/interval/__pycache__/test_interval.cpython-310.pyc
ADDED
Binary file (6.89 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/interval/__pycache__/test_interval_new.cpython-310.pyc
ADDED
Binary file (6.75 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/interval/test_interval.py
ADDED
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas._libs import index as libindex
|
5 |
+
from pandas.compat import IS64
|
6 |
+
|
7 |
+
import pandas as pd
|
8 |
+
from pandas import (
|
9 |
+
DataFrame,
|
10 |
+
IntervalIndex,
|
11 |
+
Series,
|
12 |
+
)
|
13 |
+
import pandas._testing as tm
|
14 |
+
|
15 |
+
|
16 |
+
class TestIntervalIndex:
|
17 |
+
@pytest.fixture
|
18 |
+
def series_with_interval_index(self):
|
19 |
+
return Series(np.arange(5), IntervalIndex.from_breaks(np.arange(6)))
|
20 |
+
|
21 |
+
def test_getitem_with_scalar(self, series_with_interval_index, indexer_sl):
|
22 |
+
ser = series_with_interval_index.copy()
|
23 |
+
|
24 |
+
expected = ser.iloc[:3]
|
25 |
+
tm.assert_series_equal(expected, indexer_sl(ser)[:3])
|
26 |
+
tm.assert_series_equal(expected, indexer_sl(ser)[:2.5])
|
27 |
+
tm.assert_series_equal(expected, indexer_sl(ser)[0.1:2.5])
|
28 |
+
if indexer_sl is tm.loc:
|
29 |
+
tm.assert_series_equal(expected, ser.loc[-1:3])
|
30 |
+
|
31 |
+
expected = ser.iloc[1:4]
|
32 |
+
tm.assert_series_equal(expected, indexer_sl(ser)[[1.5, 2.5, 3.5]])
|
33 |
+
tm.assert_series_equal(expected, indexer_sl(ser)[[2, 3, 4]])
|
34 |
+
tm.assert_series_equal(expected, indexer_sl(ser)[[1.5, 3, 4]])
|
35 |
+
|
36 |
+
expected = ser.iloc[2:5]
|
37 |
+
tm.assert_series_equal(expected, indexer_sl(ser)[ser >= 2])
|
38 |
+
|
39 |
+
@pytest.mark.parametrize("direction", ["increasing", "decreasing"])
|
40 |
+
def test_getitem_nonoverlapping_monotonic(self, direction, closed, indexer_sl):
|
41 |
+
tpls = [(0, 1), (2, 3), (4, 5)]
|
42 |
+
if direction == "decreasing":
|
43 |
+
tpls = tpls[::-1]
|
44 |
+
|
45 |
+
idx = IntervalIndex.from_tuples(tpls, closed=closed)
|
46 |
+
ser = Series(list("abc"), idx)
|
47 |
+
|
48 |
+
for key, expected in zip(idx.left, ser):
|
49 |
+
if idx.closed_left:
|
50 |
+
assert indexer_sl(ser)[key] == expected
|
51 |
+
else:
|
52 |
+
with pytest.raises(KeyError, match=str(key)):
|
53 |
+
indexer_sl(ser)[key]
|
54 |
+
|
55 |
+
for key, expected in zip(idx.right, ser):
|
56 |
+
if idx.closed_right:
|
57 |
+
assert indexer_sl(ser)[key] == expected
|
58 |
+
else:
|
59 |
+
with pytest.raises(KeyError, match=str(key)):
|
60 |
+
indexer_sl(ser)[key]
|
61 |
+
|
62 |
+
for key, expected in zip(idx.mid, ser):
|
63 |
+
assert indexer_sl(ser)[key] == expected
|
64 |
+
|
65 |
+
def test_getitem_non_matching(self, series_with_interval_index, indexer_sl):
|
66 |
+
ser = series_with_interval_index.copy()
|
67 |
+
|
68 |
+
# this is a departure from our current
|
69 |
+
# indexing scheme, but simpler
|
70 |
+
with pytest.raises(KeyError, match=r"\[-1\] not in index"):
|
71 |
+
indexer_sl(ser)[[-1, 3, 4, 5]]
|
72 |
+
|
73 |
+
with pytest.raises(KeyError, match=r"\[-1\] not in index"):
|
74 |
+
indexer_sl(ser)[[-1, 3]]
|
75 |
+
|
76 |
+
def test_loc_getitem_large_series(self, monkeypatch):
|
77 |
+
size_cutoff = 20
|
78 |
+
with monkeypatch.context():
|
79 |
+
monkeypatch.setattr(libindex, "_SIZE_CUTOFF", size_cutoff)
|
80 |
+
ser = Series(
|
81 |
+
np.arange(size_cutoff),
|
82 |
+
index=IntervalIndex.from_breaks(np.arange(size_cutoff + 1)),
|
83 |
+
)
|
84 |
+
|
85 |
+
result1 = ser.loc[:8]
|
86 |
+
result2 = ser.loc[0:8]
|
87 |
+
result3 = ser.loc[0:8:1]
|
88 |
+
tm.assert_series_equal(result1, result2)
|
89 |
+
tm.assert_series_equal(result1, result3)
|
90 |
+
|
91 |
+
def test_loc_getitem_frame(self):
|
92 |
+
# CategoricalIndex with IntervalIndex categories
|
93 |
+
df = DataFrame({"A": range(10)})
|
94 |
+
ser = pd.cut(df.A, 5)
|
95 |
+
df["B"] = ser
|
96 |
+
df = df.set_index("B")
|
97 |
+
|
98 |
+
result = df.loc[4]
|
99 |
+
expected = df.iloc[4:6]
|
100 |
+
tm.assert_frame_equal(result, expected)
|
101 |
+
|
102 |
+
with pytest.raises(KeyError, match="10"):
|
103 |
+
df.loc[10]
|
104 |
+
|
105 |
+
# single list-like
|
106 |
+
result = df.loc[[4]]
|
107 |
+
expected = df.iloc[4:6]
|
108 |
+
tm.assert_frame_equal(result, expected)
|
109 |
+
|
110 |
+
# non-unique
|
111 |
+
result = df.loc[[4, 5]]
|
112 |
+
expected = df.take([4, 5, 4, 5])
|
113 |
+
tm.assert_frame_equal(result, expected)
|
114 |
+
|
115 |
+
msg = (
|
116 |
+
r"None of \[Index\(\[10\], dtype='object', name='B'\)\] "
|
117 |
+
r"are in the \[index\]"
|
118 |
+
)
|
119 |
+
with pytest.raises(KeyError, match=msg):
|
120 |
+
df.loc[[10]]
|
121 |
+
|
122 |
+
# partial missing
|
123 |
+
with pytest.raises(KeyError, match=r"\[10\] not in index"):
|
124 |
+
df.loc[[10, 4]]
|
125 |
+
|
126 |
+
def test_getitem_interval_with_nans(self, frame_or_series, indexer_sl):
|
127 |
+
# GH#41831
|
128 |
+
|
129 |
+
index = IntervalIndex([np.nan, np.nan])
|
130 |
+
key = index[:-1]
|
131 |
+
|
132 |
+
obj = frame_or_series(range(2), index=index)
|
133 |
+
if frame_or_series is DataFrame and indexer_sl is tm.setitem:
|
134 |
+
obj = obj.T
|
135 |
+
|
136 |
+
result = indexer_sl(obj)[key]
|
137 |
+
expected = obj
|
138 |
+
|
139 |
+
tm.assert_equal(result, expected)
|
140 |
+
|
141 |
+
def test_setitem_interval_with_slice(self):
|
142 |
+
# GH#54722
|
143 |
+
ii = IntervalIndex.from_breaks(range(4, 15))
|
144 |
+
ser = Series(range(10), index=ii)
|
145 |
+
|
146 |
+
orig = ser.copy()
|
147 |
+
|
148 |
+
# This should be a no-op (used to raise)
|
149 |
+
ser.loc[1:3] = 20
|
150 |
+
tm.assert_series_equal(ser, orig)
|
151 |
+
|
152 |
+
ser.loc[6:8] = 19
|
153 |
+
orig.iloc[1:4] = 19
|
154 |
+
tm.assert_series_equal(ser, orig)
|
155 |
+
|
156 |
+
ser2 = Series(range(5), index=ii[::2])
|
157 |
+
orig2 = ser2.copy()
|
158 |
+
|
159 |
+
# this used to raise
|
160 |
+
ser2.loc[6:8] = 22 # <- raises on main, sets on branch
|
161 |
+
orig2.iloc[1] = 22
|
162 |
+
tm.assert_series_equal(ser2, orig2)
|
163 |
+
|
164 |
+
ser2.loc[5:7] = 21
|
165 |
+
orig2.iloc[:2] = 21
|
166 |
+
tm.assert_series_equal(ser2, orig2)
|
167 |
+
|
168 |
+
|
169 |
+
class TestIntervalIndexInsideMultiIndex:
|
170 |
+
def test_mi_intervalindex_slicing_with_scalar(self):
|
171 |
+
# GH#27456
|
172 |
+
ii = IntervalIndex.from_arrays(
|
173 |
+
[0, 1, 10, 11, 0, 1, 10, 11], [1, 2, 11, 12, 1, 2, 11, 12], name="MP"
|
174 |
+
)
|
175 |
+
idx = pd.MultiIndex.from_arrays(
|
176 |
+
[
|
177 |
+
pd.Index(["FC", "FC", "FC", "FC", "OWNER", "OWNER", "OWNER", "OWNER"]),
|
178 |
+
pd.Index(
|
179 |
+
["RID1", "RID1", "RID2", "RID2", "RID1", "RID1", "RID2", "RID2"]
|
180 |
+
),
|
181 |
+
ii,
|
182 |
+
]
|
183 |
+
)
|
184 |
+
|
185 |
+
idx.names = ["Item", "RID", "MP"]
|
186 |
+
df = DataFrame({"value": [1, 2, 3, 4, 5, 6, 7, 8]})
|
187 |
+
df.index = idx
|
188 |
+
|
189 |
+
query_df = DataFrame(
|
190 |
+
{
|
191 |
+
"Item": ["FC", "OWNER", "FC", "OWNER", "OWNER"],
|
192 |
+
"RID": ["RID1", "RID1", "RID1", "RID2", "RID2"],
|
193 |
+
"MP": [0.2, 1.5, 1.6, 11.1, 10.9],
|
194 |
+
}
|
195 |
+
)
|
196 |
+
|
197 |
+
query_df = query_df.sort_index()
|
198 |
+
|
199 |
+
idx = pd.MultiIndex.from_arrays([query_df.Item, query_df.RID, query_df.MP])
|
200 |
+
query_df.index = idx
|
201 |
+
result = df.value.loc[query_df.index]
|
202 |
+
|
203 |
+
# the IntervalIndex level is indexed with floats, which map to
|
204 |
+
# the intervals containing them. Matching the behavior we would get
|
205 |
+
# with _only_ an IntervalIndex, we get an IntervalIndex level back.
|
206 |
+
sliced_level = ii.take([0, 1, 1, 3, 2])
|
207 |
+
expected_index = pd.MultiIndex.from_arrays(
|
208 |
+
[idx.get_level_values(0), idx.get_level_values(1), sliced_level]
|
209 |
+
)
|
210 |
+
expected = Series([1, 6, 2, 8, 7], index=expected_index, name="value")
|
211 |
+
tm.assert_series_equal(result, expected)
|
212 |
+
|
213 |
+
@pytest.mark.xfail(not IS64, reason="GH 23440")
|
214 |
+
@pytest.mark.parametrize(
|
215 |
+
"base",
|
216 |
+
[101, 1010],
|
217 |
+
)
|
218 |
+
def test_reindex_behavior_with_interval_index(self, base):
|
219 |
+
# GH 51826
|
220 |
+
|
221 |
+
ser = Series(
|
222 |
+
range(base),
|
223 |
+
index=IntervalIndex.from_arrays(range(base), range(1, base + 1)),
|
224 |
+
)
|
225 |
+
expected_result = Series([np.nan, 0], index=[np.nan, 1.0], dtype=float)
|
226 |
+
result = ser.reindex(index=[np.nan, 1.0])
|
227 |
+
tm.assert_series_equal(result, expected_result)
|
llmeval-env/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)
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (205 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_chaining_and_caching.cpython-310.pyc
ADDED
Binary file (2.8 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_datetime.cpython-310.pyc
ADDED
Binary file (1.31 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_getitem.cpython-310.pyc
ADDED
Binary file (11.2 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_iloc.cpython-310.pyc
ADDED
Binary file (5.84 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_indexing_slow.cpython-310.pyc
ADDED
Binary file (3.32 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_loc.cpython-310.pyc
ADDED
Binary file (29.8 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_multiindex.cpython-310.pyc
ADDED
Binary file (7.9 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_partial.cpython-310.pyc
ADDED
Binary file (7.05 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_setitem.cpython-310.pyc
ADDED
Binary file (17 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_slice.cpython-310.pyc
ADDED
Binary file (17.2 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_sorted.cpython-310.pyc
ADDED
Binary file (5.51 kB). View file
|
|
llmeval-env/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)
|
llmeval-env/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)
|
llmeval-env/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)
|
llmeval-env/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)
|
llmeval-env/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)
|
llmeval-env/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
|
llmeval-env/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)
|
llmeval-env/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)
|
llmeval-env/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)
|
llmeval-env/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)
|
llmeval-env/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)
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/tslibs/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_ccalendar.cpython-310.pyc
ADDED
Binary file (2.15 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_conversion.cpython-310.pyc
ADDED
Binary file (4.71 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_fields.cpython-310.pyc
ADDED
Binary file (1.65 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/tslibs/__pycache__/test_npy_units.cpython-310.pyc
ADDED
Binary file (1.33 kB). View file
|
|