Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/__init__.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/common.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/conftest.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_at.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_categorical.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_chaining_and_caching.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_check_indexer.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_coercion.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_datetime.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_floats.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_iat.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_iloc.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_indexers.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_indexing.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_na_indexing.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_partial.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_scalar.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/common.py +40 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/conftest.py +104 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/interval/__init__.py +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/interval/__pycache__/__init__.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/interval/__pycache__/test_interval.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/interval/__pycache__/test_interval_new.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/interval/test_interval.py +174 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/interval/test_interval_new.py +229 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__init__.py +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_chaining_and_caching.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_getitem.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_loc.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_multiindex.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_partial.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_setitem.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_slice.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_sorted.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_chaining_and_caching.py +82 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_datetime.py +50 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_getitem.py +393 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_iloc.py +171 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_indexing_slow.py +97 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_loc.py +960 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_multiindex.py +228 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_partial.py +256 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_setitem.py +544 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_slice.py +795 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_sorted.py +153 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/test_at.py +250 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/test_chaining_and_caching.py +631 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/test_coercion.py +904 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/test_floats.py +675 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/indexing/test_iat.py +48 -0
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (177 Bytes). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/common.cpython-310.pyc
ADDED
|
Binary file (1.28 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/conftest.cpython-310.pyc
ADDED
|
Binary file (3.32 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_at.cpython-310.pyc
ADDED
|
Binary file (8.3 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_categorical.cpython-310.pyc
ADDED
|
Binary file (15.1 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_chaining_and_caching.cpython-310.pyc
ADDED
|
Binary file (18.7 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_check_indexer.cpython-310.pyc
ADDED
|
Binary file (2.86 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_coercion.cpython-310.pyc
ADDED
|
Binary file (24.3 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_datetime.cpython-310.pyc
ADDED
|
Binary file (5.36 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_floats.cpython-310.pyc
ADDED
|
Binary file (14.3 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_iat.cpython-310.pyc
ADDED
|
Binary file (1.5 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_iloc.cpython-310.pyc
ADDED
|
Binary file (43.8 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_indexers.cpython-310.pyc
ADDED
|
Binary file (2.34 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_indexing.cpython-310.pyc
ADDED
|
Binary file (30.4 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_na_indexing.cpython-310.pyc
ADDED
|
Binary file (1.94 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_partial.cpython-310.pyc
ADDED
|
Binary file (18.6 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_scalar.cpython-310.pyc
ADDED
|
Binary file (9.54 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/common.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" common utilities """
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from typing import (
|
| 5 |
+
Any,
|
| 6 |
+
Literal,
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def _mklbl(prefix: str, n: int):
|
| 11 |
+
return [f"{prefix}{i}" for i in range(n)]
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def check_indexing_smoketest_or_raises(
|
| 15 |
+
obj,
|
| 16 |
+
method: Literal["iloc", "loc"],
|
| 17 |
+
key: Any,
|
| 18 |
+
axes: Literal[0, 1] | None = None,
|
| 19 |
+
fails=None,
|
| 20 |
+
) -> None:
|
| 21 |
+
if axes is None:
|
| 22 |
+
axes_list = [0, 1]
|
| 23 |
+
else:
|
| 24 |
+
assert axes in [0, 1]
|
| 25 |
+
axes_list = [axes]
|
| 26 |
+
|
| 27 |
+
for ax in axes_list:
|
| 28 |
+
if ax < obj.ndim:
|
| 29 |
+
# create a tuple accessor
|
| 30 |
+
new_axes = [slice(None)] * obj.ndim
|
| 31 |
+
new_axes[ax] = key
|
| 32 |
+
axified = tuple(new_axes)
|
| 33 |
+
try:
|
| 34 |
+
getattr(obj, method).__getitem__(axified)
|
| 35 |
+
except (IndexError, TypeError, KeyError) as detail:
|
| 36 |
+
# if we are in fails, the ok, otherwise raise it
|
| 37 |
+
if fails is not None:
|
| 38 |
+
if isinstance(detail, fails):
|
| 39 |
+
return
|
| 40 |
+
raise
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/conftest.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from pandas import (
|
| 5 |
+
DataFrame,
|
| 6 |
+
Index,
|
| 7 |
+
MultiIndex,
|
| 8 |
+
Series,
|
| 9 |
+
date_range,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@pytest.fixture
|
| 14 |
+
def series_ints():
|
| 15 |
+
return Series(np.random.rand(4), index=np.arange(0, 8, 2))
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@pytest.fixture
|
| 19 |
+
def frame_ints():
|
| 20 |
+
return DataFrame(
|
| 21 |
+
np.random.randn(4, 4), index=np.arange(0, 8, 2), columns=np.arange(0, 12, 3)
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@pytest.fixture
|
| 26 |
+
def series_uints():
|
| 27 |
+
return Series(np.random.rand(4), index=Index(np.arange(0, 8, 2, dtype=np.uint64)))
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@pytest.fixture
|
| 31 |
+
def frame_uints():
|
| 32 |
+
return DataFrame(
|
| 33 |
+
np.random.randn(4, 4),
|
| 34 |
+
index=Index(range(0, 8, 2), dtype=np.uint64),
|
| 35 |
+
columns=Index(range(0, 12, 3), dtype=np.uint64),
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@pytest.fixture
|
| 40 |
+
def series_labels():
|
| 41 |
+
return Series(np.random.randn(4), index=list("abcd"))
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@pytest.fixture
|
| 45 |
+
def frame_labels():
|
| 46 |
+
return DataFrame(np.random.randn(4, 4), index=list("abcd"), columns=list("ABCD"))
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@pytest.fixture
|
| 50 |
+
def series_ts():
|
| 51 |
+
return Series(np.random.randn(4), index=date_range("20130101", periods=4))
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@pytest.fixture
|
| 55 |
+
def frame_ts():
|
| 56 |
+
return DataFrame(np.random.randn(4, 4), index=date_range("20130101", periods=4))
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@pytest.fixture
|
| 60 |
+
def series_floats():
|
| 61 |
+
return Series(np.random.rand(4), index=Index(range(0, 8, 2), dtype=np.float64))
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
@pytest.fixture
|
| 65 |
+
def frame_floats():
|
| 66 |
+
return DataFrame(
|
| 67 |
+
np.random.randn(4, 4),
|
| 68 |
+
index=Index(range(0, 8, 2), dtype=np.float64),
|
| 69 |
+
columns=Index(range(0, 12, 3), dtype=np.float64),
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
@pytest.fixture
|
| 74 |
+
def series_mixed():
|
| 75 |
+
return Series(np.random.randn(4), index=[2, 4, "null", 8])
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@pytest.fixture
|
| 79 |
+
def frame_mixed():
|
| 80 |
+
return DataFrame(np.random.randn(4, 4), index=[2, 4, "null", 8])
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
@pytest.fixture
|
| 84 |
+
def frame_empty():
|
| 85 |
+
return DataFrame()
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
@pytest.fixture
|
| 89 |
+
def series_empty():
|
| 90 |
+
return Series(dtype=object)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
@pytest.fixture
|
| 94 |
+
def frame_multi():
|
| 95 |
+
return DataFrame(
|
| 96 |
+
np.random.randn(4, 4),
|
| 97 |
+
index=MultiIndex.from_product([[1, 2], [3, 4]]),
|
| 98 |
+
columns=MultiIndex.from_product([[5, 6], [7, 8]]),
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
@pytest.fixture
|
| 103 |
+
def series_multi():
|
| 104 |
+
return Series(np.random.rand(4), index=MultiIndex.from_product([[1, 2], [3, 4]]))
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/interval/__init__.py
ADDED
|
File without changes
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/interval/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (186 Bytes). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/interval/__pycache__/test_interval.cpython-310.pyc
ADDED
|
Binary file (5.49 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/interval/__pycache__/test_interval_new.cpython-310.pyc
ADDED
|
Binary file (6.68 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/interval/test_interval.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from pandas import (
|
| 6 |
+
DataFrame,
|
| 7 |
+
IntervalIndex,
|
| 8 |
+
Series,
|
| 9 |
+
)
|
| 10 |
+
import pandas._testing as tm
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class TestIntervalIndex:
|
| 14 |
+
@pytest.fixture
|
| 15 |
+
def series_with_interval_index(self):
|
| 16 |
+
return Series(np.arange(5), IntervalIndex.from_breaks(np.arange(6)))
|
| 17 |
+
|
| 18 |
+
def test_getitem_with_scalar(self, series_with_interval_index, indexer_sl):
|
| 19 |
+
ser = series_with_interval_index.copy()
|
| 20 |
+
|
| 21 |
+
expected = ser.iloc[:3]
|
| 22 |
+
tm.assert_series_equal(expected, indexer_sl(ser)[:3])
|
| 23 |
+
tm.assert_series_equal(expected, indexer_sl(ser)[:2.5])
|
| 24 |
+
tm.assert_series_equal(expected, indexer_sl(ser)[0.1:2.5])
|
| 25 |
+
if indexer_sl is tm.loc:
|
| 26 |
+
tm.assert_series_equal(expected, ser.loc[-1:3])
|
| 27 |
+
|
| 28 |
+
expected = ser.iloc[1:4]
|
| 29 |
+
tm.assert_series_equal(expected, indexer_sl(ser)[[1.5, 2.5, 3.5]])
|
| 30 |
+
tm.assert_series_equal(expected, indexer_sl(ser)[[2, 3, 4]])
|
| 31 |
+
tm.assert_series_equal(expected, indexer_sl(ser)[[1.5, 3, 4]])
|
| 32 |
+
|
| 33 |
+
expected = ser.iloc[2:5]
|
| 34 |
+
tm.assert_series_equal(expected, indexer_sl(ser)[ser >= 2])
|
| 35 |
+
|
| 36 |
+
@pytest.mark.parametrize("direction", ["increasing", "decreasing"])
|
| 37 |
+
def test_getitem_nonoverlapping_monotonic(self, direction, closed, indexer_sl):
|
| 38 |
+
tpls = [(0, 1), (2, 3), (4, 5)]
|
| 39 |
+
if direction == "decreasing":
|
| 40 |
+
tpls = tpls[::-1]
|
| 41 |
+
|
| 42 |
+
idx = IntervalIndex.from_tuples(tpls, closed=closed)
|
| 43 |
+
ser = Series(list("abc"), idx)
|
| 44 |
+
|
| 45 |
+
for key, expected in zip(idx.left, ser):
|
| 46 |
+
if idx.closed_left:
|
| 47 |
+
assert indexer_sl(ser)[key] == expected
|
| 48 |
+
else:
|
| 49 |
+
with pytest.raises(KeyError, match=str(key)):
|
| 50 |
+
indexer_sl(ser)[key]
|
| 51 |
+
|
| 52 |
+
for key, expected in zip(idx.right, ser):
|
| 53 |
+
if idx.closed_right:
|
| 54 |
+
assert indexer_sl(ser)[key] == expected
|
| 55 |
+
else:
|
| 56 |
+
with pytest.raises(KeyError, match=str(key)):
|
| 57 |
+
indexer_sl(ser)[key]
|
| 58 |
+
|
| 59 |
+
for key, expected in zip(idx.mid, ser):
|
| 60 |
+
assert indexer_sl(ser)[key] == expected
|
| 61 |
+
|
| 62 |
+
def test_getitem_non_matching(self, series_with_interval_index, indexer_sl):
|
| 63 |
+
ser = series_with_interval_index.copy()
|
| 64 |
+
|
| 65 |
+
# this is a departure from our current
|
| 66 |
+
# indexing scheme, but simpler
|
| 67 |
+
with pytest.raises(KeyError, match=r"\[-1\] not in index"):
|
| 68 |
+
indexer_sl(ser)[[-1, 3, 4, 5]]
|
| 69 |
+
|
| 70 |
+
with pytest.raises(KeyError, match=r"\[-1\] not in index"):
|
| 71 |
+
indexer_sl(ser)[[-1, 3]]
|
| 72 |
+
|
| 73 |
+
@pytest.mark.slow
|
| 74 |
+
def test_loc_getitem_large_series(self):
|
| 75 |
+
ser = Series(
|
| 76 |
+
np.arange(1000000), index=IntervalIndex.from_breaks(np.arange(1000001))
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
result1 = ser.loc[:80000]
|
| 80 |
+
result2 = ser.loc[0:80000]
|
| 81 |
+
result3 = ser.loc[0:80000:1]
|
| 82 |
+
tm.assert_series_equal(result1, result2)
|
| 83 |
+
tm.assert_series_equal(result1, result3)
|
| 84 |
+
|
| 85 |
+
def test_loc_getitem_frame(self):
|
| 86 |
+
# CategoricalIndex with IntervalIndex categories
|
| 87 |
+
df = DataFrame({"A": range(10)})
|
| 88 |
+
ser = pd.cut(df.A, 5)
|
| 89 |
+
df["B"] = ser
|
| 90 |
+
df = df.set_index("B")
|
| 91 |
+
|
| 92 |
+
result = df.loc[4]
|
| 93 |
+
expected = df.iloc[4:6]
|
| 94 |
+
tm.assert_frame_equal(result, expected)
|
| 95 |
+
|
| 96 |
+
with pytest.raises(KeyError, match="10"):
|
| 97 |
+
df.loc[10]
|
| 98 |
+
|
| 99 |
+
# single list-like
|
| 100 |
+
result = df.loc[[4]]
|
| 101 |
+
expected = df.iloc[4:6]
|
| 102 |
+
tm.assert_frame_equal(result, expected)
|
| 103 |
+
|
| 104 |
+
# non-unique
|
| 105 |
+
result = df.loc[[4, 5]]
|
| 106 |
+
expected = df.take([4, 5, 4, 5])
|
| 107 |
+
tm.assert_frame_equal(result, expected)
|
| 108 |
+
|
| 109 |
+
with pytest.raises(KeyError, match=r"None of \[\[10\]\] are"):
|
| 110 |
+
df.loc[[10]]
|
| 111 |
+
|
| 112 |
+
# partial missing
|
| 113 |
+
with pytest.raises(KeyError, match=r"\[10\] not in index"):
|
| 114 |
+
df.loc[[10, 4]]
|
| 115 |
+
|
| 116 |
+
def test_getitem_interval_with_nans(self, frame_or_series, indexer_sl):
|
| 117 |
+
# GH#41831
|
| 118 |
+
|
| 119 |
+
index = IntervalIndex([np.nan, np.nan])
|
| 120 |
+
key = index[:-1]
|
| 121 |
+
|
| 122 |
+
obj = frame_or_series(range(2), index=index)
|
| 123 |
+
if frame_or_series is DataFrame and indexer_sl is tm.setitem:
|
| 124 |
+
obj = obj.T
|
| 125 |
+
|
| 126 |
+
result = indexer_sl(obj)[key]
|
| 127 |
+
expected = obj
|
| 128 |
+
|
| 129 |
+
tm.assert_equal(result, expected)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class TestIntervalIndexInsideMultiIndex:
|
| 133 |
+
def test_mi_intervalindex_slicing_with_scalar(self):
|
| 134 |
+
# GH#27456
|
| 135 |
+
ii = IntervalIndex.from_arrays(
|
| 136 |
+
[0, 1, 10, 11, 0, 1, 10, 11], [1, 2, 11, 12, 1, 2, 11, 12], name="MP"
|
| 137 |
+
)
|
| 138 |
+
idx = pd.MultiIndex.from_arrays(
|
| 139 |
+
[
|
| 140 |
+
pd.Index(["FC", "FC", "FC", "FC", "OWNER", "OWNER", "OWNER", "OWNER"]),
|
| 141 |
+
pd.Index(
|
| 142 |
+
["RID1", "RID1", "RID2", "RID2", "RID1", "RID1", "RID2", "RID2"]
|
| 143 |
+
),
|
| 144 |
+
ii,
|
| 145 |
+
]
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
idx.names = ["Item", "RID", "MP"]
|
| 149 |
+
df = DataFrame({"value": [1, 2, 3, 4, 5, 6, 7, 8]})
|
| 150 |
+
df.index = idx
|
| 151 |
+
|
| 152 |
+
query_df = DataFrame(
|
| 153 |
+
{
|
| 154 |
+
"Item": ["FC", "OWNER", "FC", "OWNER", "OWNER"],
|
| 155 |
+
"RID": ["RID1", "RID1", "RID1", "RID2", "RID2"],
|
| 156 |
+
"MP": [0.2, 1.5, 1.6, 11.1, 10.9],
|
| 157 |
+
}
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
query_df = query_df.sort_index()
|
| 161 |
+
|
| 162 |
+
idx = pd.MultiIndex.from_arrays([query_df.Item, query_df.RID, query_df.MP])
|
| 163 |
+
query_df.index = idx
|
| 164 |
+
result = df.value.loc[query_df.index]
|
| 165 |
+
|
| 166 |
+
# the IntervalIndex level is indexed with floats, which map to
|
| 167 |
+
# the intervals containing them. Matching the behavior we would get
|
| 168 |
+
# with _only_ an IntervalIndex, we get an IntervalIndex level back.
|
| 169 |
+
sliced_level = ii.take([0, 1, 1, 3, 2])
|
| 170 |
+
expected_index = pd.MultiIndex.from_arrays(
|
| 171 |
+
[idx.get_level_values(0), idx.get_level_values(1), sliced_level]
|
| 172 |
+
)
|
| 173 |
+
expected = Series([1, 6, 2, 8, 7], index=expected_index, name="value")
|
| 174 |
+
tm.assert_series_equal(result, expected)
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/interval/test_interval_new.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
result == expected
|
| 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 = r"None of \[\[Interval\(3, 5, closed='right'\)\]\]"
|
| 153 |
+
with pytest.raises(KeyError, match=msg):
|
| 154 |
+
indexer_sl(ser)[[Interval(3, 5)]]
|
| 155 |
+
|
| 156 |
+
# slices with interval (only exact matches)
|
| 157 |
+
expected = ser
|
| 158 |
+
result = indexer_sl(ser)[Interval(1, 5) : Interval(3, 7)]
|
| 159 |
+
tm.assert_series_equal(expected, result)
|
| 160 |
+
|
| 161 |
+
msg = (
|
| 162 |
+
"'can only get slices from an IntervalIndex if bounds are "
|
| 163 |
+
"non-overlapping and all monotonic increasing or decreasing'"
|
| 164 |
+
)
|
| 165 |
+
with pytest.raises(KeyError, match=msg):
|
| 166 |
+
indexer_sl(ser)[Interval(1, 6) : Interval(3, 8)]
|
| 167 |
+
|
| 168 |
+
if indexer_sl is tm.loc:
|
| 169 |
+
# slices with scalar raise for overlapping intervals
|
| 170 |
+
# TODO KeyError is the appropriate error?
|
| 171 |
+
with pytest.raises(KeyError, match=msg):
|
| 172 |
+
ser.loc[1:4]
|
| 173 |
+
|
| 174 |
+
def test_non_unique(self, indexer_sl):
|
| 175 |
+
idx = IntervalIndex.from_tuples([(1, 3), (3, 7)])
|
| 176 |
+
ser = Series(range(len(idx)), index=idx)
|
| 177 |
+
|
| 178 |
+
result = indexer_sl(ser)[Interval(1, 3)]
|
| 179 |
+
assert result == 0
|
| 180 |
+
|
| 181 |
+
result = indexer_sl(ser)[[Interval(1, 3)]]
|
| 182 |
+
expected = ser.iloc[0:1]
|
| 183 |
+
tm.assert_series_equal(expected, result)
|
| 184 |
+
|
| 185 |
+
def test_non_unique_moar(self, indexer_sl):
|
| 186 |
+
idx = IntervalIndex.from_tuples([(1, 3), (1, 3), (3, 7)])
|
| 187 |
+
ser = Series(range(len(idx)), index=idx)
|
| 188 |
+
|
| 189 |
+
expected = ser.iloc[[0, 1]]
|
| 190 |
+
result = indexer_sl(ser)[Interval(1, 3)]
|
| 191 |
+
tm.assert_series_equal(expected, result)
|
| 192 |
+
|
| 193 |
+
expected = ser
|
| 194 |
+
result = indexer_sl(ser)[Interval(1, 3) :]
|
| 195 |
+
tm.assert_series_equal(expected, result)
|
| 196 |
+
|
| 197 |
+
expected = ser.iloc[[0, 1]]
|
| 198 |
+
result = indexer_sl(ser)[[Interval(1, 3)]]
|
| 199 |
+
tm.assert_series_equal(expected, result)
|
| 200 |
+
|
| 201 |
+
def test_loc_getitem_missing_key_error_message(
|
| 202 |
+
self, frame_or_series, series_with_interval_index
|
| 203 |
+
):
|
| 204 |
+
# GH#27365
|
| 205 |
+
ser = series_with_interval_index.copy()
|
| 206 |
+
obj = frame_or_series(ser)
|
| 207 |
+
with pytest.raises(KeyError, match=r"\[6\]"):
|
| 208 |
+
obj.loc[[4, 5, 6]]
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
@pytest.mark.xfail(not IS64, reason="GH 23440")
|
| 212 |
+
@pytest.mark.parametrize(
|
| 213 |
+
"intervals",
|
| 214 |
+
[
|
| 215 |
+
([Interval(-np.inf, 0.0), Interval(0.0, 1.0)]),
|
| 216 |
+
([Interval(-np.inf, -2.0), Interval(-2.0, -1.0)]),
|
| 217 |
+
([Interval(-1.0, 0.0), Interval(0.0, np.inf)]),
|
| 218 |
+
([Interval(1.0, 2.0), Interval(2.0, np.inf)]),
|
| 219 |
+
],
|
| 220 |
+
)
|
| 221 |
+
def test_repeating_interval_index_with_infs(intervals):
|
| 222 |
+
# GH 46658
|
| 223 |
+
|
| 224 |
+
interval_index = Index(intervals * 51)
|
| 225 |
+
|
| 226 |
+
expected = np.arange(1, 102, 2, dtype=np.intp)
|
| 227 |
+
result = interval_index.get_indexer_for([intervals[1]])
|
| 228 |
+
|
| 229 |
+
tm.assert_equal(result, expected)
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__init__.py
ADDED
|
File without changes
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_chaining_and_caching.cpython-310.pyc
ADDED
|
Binary file (2.43 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_getitem.cpython-310.pyc
ADDED
|
Binary file (10.6 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_loc.cpython-310.pyc
ADDED
|
Binary file (28.9 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_multiindex.cpython-310.pyc
ADDED
|
Binary file (7.39 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_partial.cpython-310.pyc
ADDED
|
Binary file (6.89 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_setitem.cpython-310.pyc
ADDED
|
Binary file (15.8 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_slice.cpython-310.pyc
ADDED
|
Binary file (17.2 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/__pycache__/test_sorted.cpython-310.pyc
ADDED
|
Binary file (5.46 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_chaining_and_caching.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from pandas import (
|
| 8 |
+
DataFrame,
|
| 9 |
+
MultiIndex,
|
| 10 |
+
Series,
|
| 11 |
+
)
|
| 12 |
+
import pandas._testing as tm
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def test_detect_chained_assignment(using_copy_on_write):
|
| 16 |
+
# Inplace ops, originally from:
|
| 17 |
+
# https://stackoverflow.com/questions/20508968/series-fillna-in-a-multiindex-dataframe-does-not-fill-is-this-a-bug
|
| 18 |
+
a = [12, 23]
|
| 19 |
+
b = [123, None]
|
| 20 |
+
c = [1234, 2345]
|
| 21 |
+
d = [12345, 23456]
|
| 22 |
+
tuples = [("eyes", "left"), ("eyes", "right"), ("ears", "left"), ("ears", "right")]
|
| 23 |
+
events = {
|
| 24 |
+
("eyes", "left"): a,
|
| 25 |
+
("eyes", "right"): b,
|
| 26 |
+
("ears", "left"): c,
|
| 27 |
+
("ears", "right"): d,
|
| 28 |
+
}
|
| 29 |
+
multiind = MultiIndex.from_tuples(tuples, names=["part", "side"])
|
| 30 |
+
zed = DataFrame(events, index=["a", "b"], columns=multiind)
|
| 31 |
+
|
| 32 |
+
if using_copy_on_write:
|
| 33 |
+
zed["eyes"]["right"].fillna(value=555, inplace=True)
|
| 34 |
+
else:
|
| 35 |
+
msg = "A value is trying to be set on a copy of a slice from a DataFrame"
|
| 36 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
| 37 |
+
zed["eyes"]["right"].fillna(value=555, inplace=True)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@td.skip_array_manager_invalid_test # with ArrayManager df.loc[0] is not a view
|
| 41 |
+
def test_cache_updating(using_copy_on_write):
|
| 42 |
+
# 5216
|
| 43 |
+
# make sure that we don't try to set a dead cache
|
| 44 |
+
a = np.random.rand(10, 3)
|
| 45 |
+
df = DataFrame(a, columns=["x", "y", "z"])
|
| 46 |
+
df_original = df.copy()
|
| 47 |
+
tuples = [(i, j) for i in range(5) for j in range(2)]
|
| 48 |
+
index = MultiIndex.from_tuples(tuples)
|
| 49 |
+
df.index = index
|
| 50 |
+
|
| 51 |
+
# setting via chained assignment
|
| 52 |
+
# but actually works, since everything is a view
|
| 53 |
+
if using_copy_on_write:
|
| 54 |
+
with tm.raises_chained_assignment_error():
|
| 55 |
+
df.loc[0]["z"].iloc[0] = 1.0
|
| 56 |
+
assert df.loc[(0, 0), "z"] == df_original.loc[0, "z"]
|
| 57 |
+
else:
|
| 58 |
+
df.loc[0]["z"].iloc[0] = 1.0
|
| 59 |
+
result = df.loc[(0, 0), "z"]
|
| 60 |
+
assert result == 1
|
| 61 |
+
|
| 62 |
+
# correct setting
|
| 63 |
+
df.loc[(0, 0), "z"] = 2
|
| 64 |
+
result = df.loc[(0, 0), "z"]
|
| 65 |
+
assert result == 2
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@pytest.mark.slow
|
| 69 |
+
def test_indexer_caching():
|
| 70 |
+
# GH5727
|
| 71 |
+
# make sure that indexers are in the _internal_names_set
|
| 72 |
+
n = 1000001
|
| 73 |
+
arrays = (range(n), range(n))
|
| 74 |
+
index = MultiIndex.from_tuples(zip(*arrays))
|
| 75 |
+
s = Series(np.zeros(n), index=index)
|
| 76 |
+
str(s)
|
| 77 |
+
|
| 78 |
+
# setitem
|
| 79 |
+
expected = Series(np.ones(n), index=index)
|
| 80 |
+
s = Series(np.zeros(n), index=index)
|
| 81 |
+
s[s == 0] = 1
|
| 82 |
+
tm.assert_series_equal(s, expected)
|
videochat2/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.randn(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)
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_getitem.py
ADDED
|
@@ -0,0 +1,393 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.randn(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_frame_getitem_multicolumn_empty_level():
|
| 149 |
+
df = DataFrame({"a": ["1", "2", "3"], "b": ["2", "3", "4"]})
|
| 150 |
+
df.columns = [
|
| 151 |
+
["level1 item1", "level1 item2"],
|
| 152 |
+
["", "level2 item2"],
|
| 153 |
+
["level3 item1", "level3 item2"],
|
| 154 |
+
]
|
| 155 |
+
|
| 156 |
+
result = df["level1 item1"]
|
| 157 |
+
expected = DataFrame(
|
| 158 |
+
[["1"], ["2"], ["3"]], index=df.index, columns=["level3 item1"]
|
| 159 |
+
)
|
| 160 |
+
tm.assert_frame_equal(result, expected)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
@pytest.mark.parametrize(
|
| 164 |
+
"indexer,expected_slice",
|
| 165 |
+
[
|
| 166 |
+
(lambda df: df["foo"], slice(3)),
|
| 167 |
+
(lambda df: df["bar"], slice(3, 5)),
|
| 168 |
+
(lambda df: df.loc[:, "bar"], slice(3, 5)),
|
| 169 |
+
],
|
| 170 |
+
)
|
| 171 |
+
def test_frame_getitem_toplevel(
|
| 172 |
+
multiindex_dataframe_random_data, indexer, expected_slice
|
| 173 |
+
):
|
| 174 |
+
df = multiindex_dataframe_random_data.T
|
| 175 |
+
expected = df.reindex(columns=df.columns[expected_slice])
|
| 176 |
+
expected.columns = expected.columns.droplevel(0)
|
| 177 |
+
result = indexer(df)
|
| 178 |
+
tm.assert_frame_equal(result, expected)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def test_frame_mixed_depth_get():
|
| 182 |
+
arrays = [
|
| 183 |
+
["a", "top", "top", "routine1", "routine1", "routine2"],
|
| 184 |
+
["", "OD", "OD", "result1", "result2", "result1"],
|
| 185 |
+
["", "wx", "wy", "", "", ""],
|
| 186 |
+
]
|
| 187 |
+
|
| 188 |
+
tuples = sorted(zip(*arrays))
|
| 189 |
+
index = MultiIndex.from_tuples(tuples)
|
| 190 |
+
df = DataFrame(np.random.randn(4, 6), columns=index)
|
| 191 |
+
|
| 192 |
+
result = df["a"]
|
| 193 |
+
expected = df["a", "", ""].rename("a")
|
| 194 |
+
tm.assert_series_equal(result, expected)
|
| 195 |
+
|
| 196 |
+
result = df["routine1", "result1"]
|
| 197 |
+
expected = df["routine1", "result1", ""]
|
| 198 |
+
expected = expected.rename(("routine1", "result1"))
|
| 199 |
+
tm.assert_series_equal(result, expected)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def test_frame_getitem_nan_multiindex(nulls_fixture):
|
| 203 |
+
# GH#29751
|
| 204 |
+
# loc on a multiindex containing nan values
|
| 205 |
+
n = nulls_fixture # for code readability
|
| 206 |
+
cols = ["a", "b", "c"]
|
| 207 |
+
df = DataFrame(
|
| 208 |
+
[[11, n, 13], [21, n, 23], [31, n, 33], [41, n, 43]],
|
| 209 |
+
columns=cols,
|
| 210 |
+
).set_index(["a", "b"])
|
| 211 |
+
df["c"] = df["c"].astype("int64")
|
| 212 |
+
|
| 213 |
+
idx = (21, n)
|
| 214 |
+
result = df.loc[:idx]
|
| 215 |
+
expected = DataFrame([[11, n, 13], [21, n, 23]], columns=cols).set_index(["a", "b"])
|
| 216 |
+
expected["c"] = expected["c"].astype("int64")
|
| 217 |
+
tm.assert_frame_equal(result, expected)
|
| 218 |
+
|
| 219 |
+
result = df.loc[idx:]
|
| 220 |
+
expected = DataFrame(
|
| 221 |
+
[[21, n, 23], [31, n, 33], [41, n, 43]], columns=cols
|
| 222 |
+
).set_index(["a", "b"])
|
| 223 |
+
expected["c"] = expected["c"].astype("int64")
|
| 224 |
+
tm.assert_frame_equal(result, expected)
|
| 225 |
+
|
| 226 |
+
idx1, idx2 = (21, n), (31, n)
|
| 227 |
+
result = df.loc[idx1:idx2]
|
| 228 |
+
expected = DataFrame([[21, n, 23], [31, n, 33]], columns=cols).set_index(["a", "b"])
|
| 229 |
+
expected["c"] = expected["c"].astype("int64")
|
| 230 |
+
tm.assert_frame_equal(result, expected)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
@pytest.mark.parametrize(
|
| 234 |
+
"indexer,expected",
|
| 235 |
+
[
|
| 236 |
+
(
|
| 237 |
+
(["b"], ["bar", np.nan]),
|
| 238 |
+
(
|
| 239 |
+
DataFrame(
|
| 240 |
+
[[2, 3], [5, 6]],
|
| 241 |
+
columns=MultiIndex.from_tuples([("b", "bar"), ("b", np.nan)]),
|
| 242 |
+
dtype="int64",
|
| 243 |
+
)
|
| 244 |
+
),
|
| 245 |
+
),
|
| 246 |
+
(
|
| 247 |
+
(["a", "b"]),
|
| 248 |
+
(
|
| 249 |
+
DataFrame(
|
| 250 |
+
[[1, 2, 3], [4, 5, 6]],
|
| 251 |
+
columns=MultiIndex.from_tuples(
|
| 252 |
+
[("a", "foo"), ("b", "bar"), ("b", np.nan)]
|
| 253 |
+
),
|
| 254 |
+
dtype="int64",
|
| 255 |
+
)
|
| 256 |
+
),
|
| 257 |
+
),
|
| 258 |
+
(
|
| 259 |
+
(["b"]),
|
| 260 |
+
(
|
| 261 |
+
DataFrame(
|
| 262 |
+
[[2, 3], [5, 6]],
|
| 263 |
+
columns=MultiIndex.from_tuples([("b", "bar"), ("b", np.nan)]),
|
| 264 |
+
dtype="int64",
|
| 265 |
+
)
|
| 266 |
+
),
|
| 267 |
+
),
|
| 268 |
+
(
|
| 269 |
+
(["b"], ["bar"]),
|
| 270 |
+
(
|
| 271 |
+
DataFrame(
|
| 272 |
+
[[2], [5]],
|
| 273 |
+
columns=MultiIndex.from_tuples([("b", "bar")]),
|
| 274 |
+
dtype="int64",
|
| 275 |
+
)
|
| 276 |
+
),
|
| 277 |
+
),
|
| 278 |
+
(
|
| 279 |
+
(["b"], [np.nan]),
|
| 280 |
+
(
|
| 281 |
+
DataFrame(
|
| 282 |
+
[[3], [6]],
|
| 283 |
+
columns=MultiIndex(
|
| 284 |
+
codes=[[1], [-1]], levels=[["a", "b"], ["bar", "foo"]]
|
| 285 |
+
),
|
| 286 |
+
dtype="int64",
|
| 287 |
+
)
|
| 288 |
+
),
|
| 289 |
+
),
|
| 290 |
+
(("b", np.nan), Series([3, 6], dtype="int64", name=("b", np.nan))),
|
| 291 |
+
],
|
| 292 |
+
)
|
| 293 |
+
def test_frame_getitem_nan_cols_multiindex(
|
| 294 |
+
indexer,
|
| 295 |
+
expected,
|
| 296 |
+
nulls_fixture,
|
| 297 |
+
):
|
| 298 |
+
# Slicing MultiIndex including levels with nan values, for more information
|
| 299 |
+
# see GH#25154
|
| 300 |
+
df = DataFrame(
|
| 301 |
+
[[1, 2, 3], [4, 5, 6]],
|
| 302 |
+
columns=MultiIndex.from_tuples(
|
| 303 |
+
[("a", "foo"), ("b", "bar"), ("b", nulls_fixture)]
|
| 304 |
+
),
|
| 305 |
+
dtype="int64",
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
result = df.loc[:, indexer]
|
| 309 |
+
tm.assert_equal(result, expected)
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
# ----------------------------------------------------------------------------
|
| 313 |
+
# test indexing of DataFrame with multi-level Index with duplicates
|
| 314 |
+
# ----------------------------------------------------------------------------
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
@pytest.fixture
|
| 318 |
+
def dataframe_with_duplicate_index():
|
| 319 |
+
"""Fixture for DataFrame used in tests for gh-4145 and gh-4146"""
|
| 320 |
+
data = [["a", "d", "e", "c", "f", "b"], [1, 4, 5, 3, 6, 2], [1, 4, 5, 3, 6, 2]]
|
| 321 |
+
index = ["h1", "h3", "h5"]
|
| 322 |
+
columns = MultiIndex(
|
| 323 |
+
levels=[["A", "B"], ["A1", "A2", "B1", "B2"]],
|
| 324 |
+
codes=[[0, 0, 0, 1, 1, 1], [0, 3, 3, 0, 1, 2]],
|
| 325 |
+
names=["main", "sub"],
|
| 326 |
+
)
|
| 327 |
+
return DataFrame(data, index=index, columns=columns)
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
@pytest.mark.parametrize(
|
| 331 |
+
"indexer", [lambda df: df[("A", "A1")], lambda df: df.loc[:, ("A", "A1")]]
|
| 332 |
+
)
|
| 333 |
+
def test_frame_mi_access(dataframe_with_duplicate_index, indexer):
|
| 334 |
+
# GH 4145
|
| 335 |
+
df = dataframe_with_duplicate_index
|
| 336 |
+
index = Index(["h1", "h3", "h5"])
|
| 337 |
+
columns = MultiIndex.from_tuples([("A", "A1")], names=["main", "sub"])
|
| 338 |
+
expected = DataFrame([["a", 1, 1]], index=columns, columns=index).T
|
| 339 |
+
|
| 340 |
+
result = indexer(df)
|
| 341 |
+
tm.assert_frame_equal(result, expected)
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def test_frame_mi_access_returns_series(dataframe_with_duplicate_index):
|
| 345 |
+
# GH 4146, not returning a block manager when selecting a unique index
|
| 346 |
+
# from a duplicate index
|
| 347 |
+
# as of 4879, this returns a Series (which is similar to what happens
|
| 348 |
+
# with a non-unique)
|
| 349 |
+
df = dataframe_with_duplicate_index
|
| 350 |
+
expected = Series(["a", 1, 1], index=["h1", "h3", "h5"], name="A1")
|
| 351 |
+
result = df["A"]["A1"]
|
| 352 |
+
tm.assert_series_equal(result, expected)
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def test_frame_mi_access_returns_frame(dataframe_with_duplicate_index):
|
| 356 |
+
# selecting a non_unique from the 2nd level
|
| 357 |
+
df = dataframe_with_duplicate_index
|
| 358 |
+
expected = DataFrame(
|
| 359 |
+
[["d", 4, 4], ["e", 5, 5]],
|
| 360 |
+
index=Index(["B2", "B2"], name="sub"),
|
| 361 |
+
columns=["h1", "h3", "h5"],
|
| 362 |
+
).T
|
| 363 |
+
result = df["A"]["B2"]
|
| 364 |
+
tm.assert_frame_equal(result, expected)
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def test_frame_mi_empty_slice():
|
| 368 |
+
# GH 15454
|
| 369 |
+
df = DataFrame(0, index=range(2), columns=MultiIndex.from_product([[1], [2]]))
|
| 370 |
+
result = df[[]]
|
| 371 |
+
expected = DataFrame(
|
| 372 |
+
index=[0, 1], columns=MultiIndex(levels=[[1], [2]], codes=[[], []])
|
| 373 |
+
)
|
| 374 |
+
tm.assert_frame_equal(result, expected)
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def test_loc_empty_multiindex():
|
| 378 |
+
# GH#36936
|
| 379 |
+
arrays = [["a", "a", "b", "a"], ["a", "a", "b", "b"]]
|
| 380 |
+
index = MultiIndex.from_arrays(arrays, names=("idx1", "idx2"))
|
| 381 |
+
df = DataFrame([1, 2, 3, 4], index=index, columns=["value"])
|
| 382 |
+
|
| 383 |
+
# loc on empty multiindex == loc with False mask
|
| 384 |
+
empty_multiindex = df.loc[df.loc[:, "value"] == 0, :].index
|
| 385 |
+
result = df.loc[empty_multiindex, :]
|
| 386 |
+
expected = df.loc[[False] * len(df.index), :]
|
| 387 |
+
tm.assert_frame_equal(result, expected)
|
| 388 |
+
|
| 389 |
+
# replacing value with loc on empty multiindex
|
| 390 |
+
df.loc[df.loc[df.loc[:, "value"] == 0].index, "value"] = 5
|
| 391 |
+
result = df
|
| 392 |
+
expected = DataFrame([1, 2, 3, 4], index=index, columns=["value"])
|
| 393 |
+
tm.assert_frame_equal(result, expected)
|
videochat2/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.randn(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.randn(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.randn(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)
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_indexing_slow.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import (
|
| 2 |
+
Any,
|
| 3 |
+
List,
|
| 4 |
+
)
|
| 5 |
+
import warnings
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import pytest
|
| 9 |
+
|
| 10 |
+
import pandas as pd
|
| 11 |
+
from pandas import (
|
| 12 |
+
DataFrame,
|
| 13 |
+
Series,
|
| 14 |
+
)
|
| 15 |
+
import pandas._testing as tm
|
| 16 |
+
|
| 17 |
+
m = 50
|
| 18 |
+
n = 1000
|
| 19 |
+
cols = ["jim", "joe", "jolie", "joline", "jolia"]
|
| 20 |
+
|
| 21 |
+
vals: List[Any] = [
|
| 22 |
+
np.random.randint(0, 10, n),
|
| 23 |
+
np.random.choice(list("abcdefghij"), n),
|
| 24 |
+
np.random.choice(pd.date_range("20141009", periods=10).tolist(), n),
|
| 25 |
+
np.random.choice(list("ZYXWVUTSRQ"), n),
|
| 26 |
+
np.random.randn(n),
|
| 27 |
+
]
|
| 28 |
+
vals = list(map(tuple, zip(*vals)))
|
| 29 |
+
|
| 30 |
+
# bunch of keys for testing
|
| 31 |
+
keys: List[Any] = [
|
| 32 |
+
np.random.randint(0, 11, m),
|
| 33 |
+
np.random.choice(list("abcdefghijk"), m),
|
| 34 |
+
np.random.choice(pd.date_range("20141009", periods=11).tolist(), m),
|
| 35 |
+
np.random.choice(list("ZYXWVUTSRQP"), m),
|
| 36 |
+
]
|
| 37 |
+
keys = list(map(tuple, zip(*keys)))
|
| 38 |
+
keys += list(map(lambda t: t[:-1], vals[:: n // m]))
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# covers both unique index and non-unique index
|
| 42 |
+
df = DataFrame(vals, columns=cols)
|
| 43 |
+
a = pd.concat([df, df])
|
| 44 |
+
b = df.drop_duplicates(subset=cols[:-1])
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def validate(mi, df, key):
|
| 48 |
+
# check indexing into a multi-index before & past the lexsort depth
|
| 49 |
+
|
| 50 |
+
mask = np.ones(len(df)).astype("bool")
|
| 51 |
+
|
| 52 |
+
# test for all partials of this key
|
| 53 |
+
for i, k in enumerate(key):
|
| 54 |
+
mask &= df.iloc[:, i] == k
|
| 55 |
+
|
| 56 |
+
if not mask.any():
|
| 57 |
+
assert key[: i + 1] not in mi.index
|
| 58 |
+
continue
|
| 59 |
+
|
| 60 |
+
assert key[: i + 1] in mi.index
|
| 61 |
+
right = df[mask].copy()
|
| 62 |
+
|
| 63 |
+
if i + 1 != len(key): # partial key
|
| 64 |
+
return_value = right.drop(cols[: i + 1], axis=1, inplace=True)
|
| 65 |
+
assert return_value is None
|
| 66 |
+
return_value = right.set_index(cols[i + 1 : -1], inplace=True)
|
| 67 |
+
assert return_value is None
|
| 68 |
+
tm.assert_frame_equal(mi.loc[key[: i + 1]], right)
|
| 69 |
+
|
| 70 |
+
else: # full key
|
| 71 |
+
return_value = right.set_index(cols[:-1], inplace=True)
|
| 72 |
+
assert return_value is None
|
| 73 |
+
if len(right) == 1: # single hit
|
| 74 |
+
right = Series(
|
| 75 |
+
right["jolia"].values, name=right.index[0], index=["jolia"]
|
| 76 |
+
)
|
| 77 |
+
tm.assert_series_equal(mi.loc[key[: i + 1]], right)
|
| 78 |
+
else: # multi hit
|
| 79 |
+
tm.assert_frame_equal(mi.loc[key[: i + 1]], right)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@pytest.mark.filterwarnings("ignore::pandas.errors.PerformanceWarning")
|
| 83 |
+
@pytest.mark.parametrize("lexsort_depth", list(range(5)))
|
| 84 |
+
@pytest.mark.parametrize("key", keys)
|
| 85 |
+
@pytest.mark.parametrize("frame", [a, b])
|
| 86 |
+
def test_multiindex_get_loc(lexsort_depth, key, frame):
|
| 87 |
+
# GH7724, GH2646
|
| 88 |
+
|
| 89 |
+
with warnings.catch_warnings(record=True):
|
| 90 |
+
if lexsort_depth == 0:
|
| 91 |
+
df = frame.copy()
|
| 92 |
+
else:
|
| 93 |
+
df = frame.sort_values(by=cols[:lexsort_depth])
|
| 94 |
+
|
| 95 |
+
mi = df.set_index(cols[:-1])
|
| 96 |
+
assert not mi.index._lexsort_depth < lexsort_depth
|
| 97 |
+
validate(mi, df, key)
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_loc.py
ADDED
|
@@ -0,0 +1,960 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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(
|
| 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.randn(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.randn(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.randn(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.randn(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.randn(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.randn(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.randn(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(np.random.randn(len(single_level)), index=single_level)
|
| 283 |
+
for k in single_level.values:
|
| 284 |
+
s[k]
|
| 285 |
+
|
| 286 |
+
def test_loc_getitem_int_slice(self):
|
| 287 |
+
# GH 3053
|
| 288 |
+
# loc should treat integer slices like label slices
|
| 289 |
+
|
| 290 |
+
index = MultiIndex.from_product([[6, 7, 8], ["a", "b"]])
|
| 291 |
+
df = DataFrame(np.random.randn(6, 6), index, index)
|
| 292 |
+
result = df.loc[6:8, :]
|
| 293 |
+
expected = df
|
| 294 |
+
tm.assert_frame_equal(result, expected)
|
| 295 |
+
|
| 296 |
+
index = MultiIndex.from_product([[10, 20, 30], ["a", "b"]])
|
| 297 |
+
df = DataFrame(np.random.randn(6, 6), index, index)
|
| 298 |
+
result = df.loc[20:30, :]
|
| 299 |
+
expected = df.iloc[2:]
|
| 300 |
+
tm.assert_frame_equal(result, expected)
|
| 301 |
+
|
| 302 |
+
# doc examples
|
| 303 |
+
result = df.loc[10, :]
|
| 304 |
+
expected = df.iloc[0:2]
|
| 305 |
+
expected.index = ["a", "b"]
|
| 306 |
+
tm.assert_frame_equal(result, expected)
|
| 307 |
+
|
| 308 |
+
result = df.loc[:, 10]
|
| 309 |
+
expected = df[10]
|
| 310 |
+
tm.assert_frame_equal(result, expected)
|
| 311 |
+
|
| 312 |
+
@pytest.mark.parametrize(
|
| 313 |
+
"indexer_type_1", (list, tuple, set, slice, np.ndarray, Series, Index)
|
| 314 |
+
)
|
| 315 |
+
@pytest.mark.parametrize(
|
| 316 |
+
"indexer_type_2", (list, tuple, set, slice, np.ndarray, Series, Index)
|
| 317 |
+
)
|
| 318 |
+
def test_loc_getitem_nested_indexer(self, indexer_type_1, indexer_type_2):
|
| 319 |
+
# GH #19686
|
| 320 |
+
# .loc should work with nested indexers which can be
|
| 321 |
+
# any list-like objects (see `is_list_like` (`pandas.api.types`)) or slices
|
| 322 |
+
|
| 323 |
+
def convert_nested_indexer(indexer_type, keys):
|
| 324 |
+
if indexer_type == np.ndarray:
|
| 325 |
+
return np.array(keys)
|
| 326 |
+
if indexer_type == slice:
|
| 327 |
+
return slice(*keys)
|
| 328 |
+
return indexer_type(keys)
|
| 329 |
+
|
| 330 |
+
a = [10, 20, 30]
|
| 331 |
+
b = [1, 2, 3]
|
| 332 |
+
index = MultiIndex.from_product([a, b])
|
| 333 |
+
df = DataFrame(
|
| 334 |
+
np.arange(len(index), dtype="int64"), index=index, columns=["Data"]
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
keys = ([10, 20], [2, 3])
|
| 338 |
+
types = (indexer_type_1, indexer_type_2)
|
| 339 |
+
|
| 340 |
+
# check indexers with all the combinations of nested objects
|
| 341 |
+
# of all the valid types
|
| 342 |
+
indexer = tuple(
|
| 343 |
+
convert_nested_indexer(indexer_type, k)
|
| 344 |
+
for indexer_type, k in zip(types, keys)
|
| 345 |
+
)
|
| 346 |
+
if indexer_type_1 is set or indexer_type_2 is set:
|
| 347 |
+
with pytest.raises(TypeError, match="as an indexer is not supported"):
|
| 348 |
+
df.loc[indexer, "Data"]
|
| 349 |
+
|
| 350 |
+
return
|
| 351 |
+
else:
|
| 352 |
+
result = df.loc[indexer, "Data"]
|
| 353 |
+
expected = Series(
|
| 354 |
+
[1, 2, 4, 5], name="Data", index=MultiIndex.from_product(keys)
|
| 355 |
+
)
|
| 356 |
+
|
| 357 |
+
tm.assert_series_equal(result, expected)
|
| 358 |
+
|
| 359 |
+
def test_multiindex_loc_one_dimensional_tuple(self, frame_or_series):
|
| 360 |
+
# GH#37711
|
| 361 |
+
mi = MultiIndex.from_tuples([("a", "A"), ("b", "A")])
|
| 362 |
+
obj = frame_or_series([1, 2], index=mi)
|
| 363 |
+
obj.loc[("a",)] = 0
|
| 364 |
+
expected = frame_or_series([0, 2], index=mi)
|
| 365 |
+
tm.assert_equal(obj, expected)
|
| 366 |
+
|
| 367 |
+
@pytest.mark.parametrize("indexer", [("a",), ("a")])
|
| 368 |
+
def test_multiindex_one_dimensional_tuple_columns(self, indexer):
|
| 369 |
+
# GH#37711
|
| 370 |
+
mi = MultiIndex.from_tuples([("a", "A"), ("b", "A")])
|
| 371 |
+
obj = DataFrame([1, 2], index=mi)
|
| 372 |
+
obj.loc[indexer, :] = 0
|
| 373 |
+
expected = DataFrame([0, 2], index=mi)
|
| 374 |
+
tm.assert_frame_equal(obj, expected)
|
| 375 |
+
|
| 376 |
+
@pytest.mark.parametrize(
|
| 377 |
+
"indexer, exp_value", [(slice(None), 1.0), ((1, 2), np.nan)]
|
| 378 |
+
)
|
| 379 |
+
def test_multiindex_setitem_columns_enlarging(self, indexer, exp_value):
|
| 380 |
+
# GH#39147
|
| 381 |
+
mi = MultiIndex.from_tuples([(1, 2), (3, 4)])
|
| 382 |
+
df = DataFrame([[1, 2], [3, 4]], index=mi, columns=["a", "b"])
|
| 383 |
+
df.loc[indexer, ["c", "d"]] = 1.0
|
| 384 |
+
expected = DataFrame(
|
| 385 |
+
[[1, 2, 1.0, 1.0], [3, 4, exp_value, exp_value]],
|
| 386 |
+
index=mi,
|
| 387 |
+
columns=["a", "b", "c", "d"],
|
| 388 |
+
)
|
| 389 |
+
tm.assert_frame_equal(df, expected)
|
| 390 |
+
|
| 391 |
+
def test_sorted_multiindex_after_union(self):
|
| 392 |
+
# GH#44752
|
| 393 |
+
midx = MultiIndex.from_product(
|
| 394 |
+
[pd.date_range("20110101", periods=2), Index(["a", "b"])]
|
| 395 |
+
)
|
| 396 |
+
ser1 = Series(1, index=midx)
|
| 397 |
+
ser2 = Series(1, index=midx[:2])
|
| 398 |
+
df = pd.concat([ser1, ser2], axis=1)
|
| 399 |
+
expected = df.copy()
|
| 400 |
+
result = df.loc["2011-01-01":"2011-01-02"]
|
| 401 |
+
tm.assert_frame_equal(result, expected)
|
| 402 |
+
|
| 403 |
+
df = DataFrame({0: ser1, 1: ser2})
|
| 404 |
+
result = df.loc["2011-01-01":"2011-01-02"]
|
| 405 |
+
tm.assert_frame_equal(result, expected)
|
| 406 |
+
|
| 407 |
+
df = pd.concat([ser1, ser2.reindex(ser1.index)], axis=1)
|
| 408 |
+
result = df.loc["2011-01-01":"2011-01-02"]
|
| 409 |
+
tm.assert_frame_equal(result, expected)
|
| 410 |
+
|
| 411 |
+
def test_loc_no_second_level_index(self):
|
| 412 |
+
# GH#43599
|
| 413 |
+
df = DataFrame(
|
| 414 |
+
index=MultiIndex.from_product([list("ab"), list("cd"), list("e")]),
|
| 415 |
+
columns=["Val"],
|
| 416 |
+
)
|
| 417 |
+
res = df.loc[np.s_[:, "c", :]]
|
| 418 |
+
expected = DataFrame(
|
| 419 |
+
index=MultiIndex.from_product([list("ab"), list("e")]), columns=["Val"]
|
| 420 |
+
)
|
| 421 |
+
tm.assert_frame_equal(res, expected)
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
@pytest.mark.parametrize(
|
| 425 |
+
"indexer, pos",
|
| 426 |
+
[
|
| 427 |
+
([], []), # empty ok
|
| 428 |
+
(["A"], slice(3)),
|
| 429 |
+
(["A", "D"], []), # "D" isn't present -> raise
|
| 430 |
+
(["D", "E"], []), # no values found -> raise
|
| 431 |
+
(["D"], []), # same, with single item list: GH 27148
|
| 432 |
+
(pd.IndexSlice[:, ["foo"]], slice(2, None, 3)),
|
| 433 |
+
(pd.IndexSlice[:, ["foo", "bah"]], slice(2, None, 3)),
|
| 434 |
+
],
|
| 435 |
+
)
|
| 436 |
+
def test_loc_getitem_duplicates_multiindex_missing_indexers(indexer, pos):
|
| 437 |
+
# GH 7866
|
| 438 |
+
# multi-index slicing with missing indexers
|
| 439 |
+
idx = MultiIndex.from_product(
|
| 440 |
+
[["A", "B", "C"], ["foo", "bar", "baz"]], names=["one", "two"]
|
| 441 |
+
)
|
| 442 |
+
ser = Series(np.arange(9, dtype="int64"), index=idx).sort_index()
|
| 443 |
+
expected = ser.iloc[pos]
|
| 444 |
+
|
| 445 |
+
if expected.size == 0 and indexer != []:
|
| 446 |
+
with pytest.raises(KeyError, match=str(indexer)):
|
| 447 |
+
ser.loc[indexer]
|
| 448 |
+
elif indexer == (slice(None), ["foo", "bah"]):
|
| 449 |
+
# "bah" is not in idx.levels[1], raising KeyError enforced in 2.0
|
| 450 |
+
with pytest.raises(KeyError, match="'bah'"):
|
| 451 |
+
ser.loc[indexer]
|
| 452 |
+
else:
|
| 453 |
+
result = ser.loc[indexer]
|
| 454 |
+
tm.assert_series_equal(result, expected)
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
@pytest.mark.parametrize("columns_indexer", [([], slice(None)), (["foo"], [])])
|
| 458 |
+
def test_loc_getitem_duplicates_multiindex_empty_indexer(columns_indexer):
|
| 459 |
+
# GH 8737
|
| 460 |
+
# empty indexer
|
| 461 |
+
multi_index = MultiIndex.from_product((["foo", "bar", "baz"], ["alpha", "beta"]))
|
| 462 |
+
df = DataFrame(np.random.randn(5, 6), index=range(5), columns=multi_index)
|
| 463 |
+
df = df.sort_index(level=0, axis=1)
|
| 464 |
+
|
| 465 |
+
expected = DataFrame(index=range(5), columns=multi_index.reindex([])[0])
|
| 466 |
+
result = df.loc[:, columns_indexer]
|
| 467 |
+
tm.assert_frame_equal(result, expected)
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
def test_loc_getitem_duplicates_multiindex_non_scalar_type_object():
|
| 471 |
+
# regression from < 0.14.0
|
| 472 |
+
# GH 7914
|
| 473 |
+
df = DataFrame(
|
| 474 |
+
[[np.mean, np.median], ["mean", "median"]],
|
| 475 |
+
columns=MultiIndex.from_tuples([("functs", "mean"), ("functs", "median")]),
|
| 476 |
+
index=["function", "name"],
|
| 477 |
+
)
|
| 478 |
+
result = df.loc["function", ("functs", "mean")]
|
| 479 |
+
expected = np.mean
|
| 480 |
+
assert result == expected
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
def test_loc_getitem_tuple_plus_slice():
|
| 484 |
+
# GH 671
|
| 485 |
+
df = DataFrame(
|
| 486 |
+
{
|
| 487 |
+
"a": np.arange(10),
|
| 488 |
+
"b": np.arange(10),
|
| 489 |
+
"c": np.random.randn(10),
|
| 490 |
+
"d": np.random.randn(10),
|
| 491 |
+
}
|
| 492 |
+
).set_index(["a", "b"])
|
| 493 |
+
expected = df.loc[0, 0]
|
| 494 |
+
result = df.loc[(0, 0), :]
|
| 495 |
+
tm.assert_series_equal(result, expected)
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
def test_loc_getitem_int(frame_random_data_integer_multi_index):
|
| 499 |
+
df = frame_random_data_integer_multi_index
|
| 500 |
+
result = df.loc[1]
|
| 501 |
+
expected = df[-3:]
|
| 502 |
+
expected.index = expected.index.droplevel(0)
|
| 503 |
+
tm.assert_frame_equal(result, expected)
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
def test_loc_getitem_int_raises_exception(frame_random_data_integer_multi_index):
|
| 507 |
+
df = frame_random_data_integer_multi_index
|
| 508 |
+
with pytest.raises(KeyError, match=r"^3$"):
|
| 509 |
+
df.loc[3]
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
def test_loc_getitem_lowerdim_corner(multiindex_dataframe_random_data):
|
| 513 |
+
df = multiindex_dataframe_random_data
|
| 514 |
+
|
| 515 |
+
# test setup - check key not in dataframe
|
| 516 |
+
with pytest.raises(KeyError, match=r"^\('bar', 'three'\)$"):
|
| 517 |
+
df.loc[("bar", "three"), "B"]
|
| 518 |
+
|
| 519 |
+
# in theory should be inserting in a sorted space????
|
| 520 |
+
df.loc[("bar", "three"), "B"] = 0
|
| 521 |
+
expected = 0
|
| 522 |
+
result = df.sort_index().loc[("bar", "three"), "B"]
|
| 523 |
+
assert result == expected
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
def test_loc_setitem_single_column_slice():
|
| 527 |
+
# case from https://github.com/pandas-dev/pandas/issues/27841
|
| 528 |
+
df = DataFrame(
|
| 529 |
+
"string",
|
| 530 |
+
index=list("abcd"),
|
| 531 |
+
columns=MultiIndex.from_product([["Main"], ("another", "one")]),
|
| 532 |
+
)
|
| 533 |
+
df["labels"] = "a"
|
| 534 |
+
df.loc[:, "labels"] = df.index
|
| 535 |
+
tm.assert_numpy_array_equal(np.asarray(df["labels"]), np.asarray(df.index))
|
| 536 |
+
|
| 537 |
+
# test with non-object block
|
| 538 |
+
df = DataFrame(
|
| 539 |
+
np.nan,
|
| 540 |
+
index=range(4),
|
| 541 |
+
columns=MultiIndex.from_tuples([("A", "1"), ("A", "2"), ("B", "1")]),
|
| 542 |
+
)
|
| 543 |
+
expected = df.copy()
|
| 544 |
+
df.loc[:, "B"] = np.arange(4)
|
| 545 |
+
expected.iloc[:, 2] = np.arange(4)
|
| 546 |
+
tm.assert_frame_equal(df, expected)
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
def test_loc_nan_multiindex():
|
| 550 |
+
# GH 5286
|
| 551 |
+
tups = [
|
| 552 |
+
("Good Things", "C", np.nan),
|
| 553 |
+
("Good Things", "R", np.nan),
|
| 554 |
+
("Bad Things", "C", np.nan),
|
| 555 |
+
("Bad Things", "T", np.nan),
|
| 556 |
+
("Okay Things", "N", "B"),
|
| 557 |
+
("Okay Things", "N", "D"),
|
| 558 |
+
("Okay Things", "B", np.nan),
|
| 559 |
+
("Okay Things", "D", np.nan),
|
| 560 |
+
]
|
| 561 |
+
df = DataFrame(
|
| 562 |
+
np.ones((8, 4)),
|
| 563 |
+
columns=Index(["d1", "d2", "d3", "d4"]),
|
| 564 |
+
index=MultiIndex.from_tuples(tups, names=["u1", "u2", "u3"]),
|
| 565 |
+
)
|
| 566 |
+
result = df.loc["Good Things"].loc["C"]
|
| 567 |
+
expected = DataFrame(
|
| 568 |
+
np.ones((1, 4)),
|
| 569 |
+
index=Index([np.nan], dtype="object", name="u3"),
|
| 570 |
+
columns=Index(["d1", "d2", "d3", "d4"], dtype="object"),
|
| 571 |
+
)
|
| 572 |
+
tm.assert_frame_equal(result, expected)
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
def test_loc_period_string_indexing():
|
| 576 |
+
# GH 9892
|
| 577 |
+
a = pd.period_range("2013Q1", "2013Q4", freq="Q")
|
| 578 |
+
i = (1111, 2222, 3333)
|
| 579 |
+
idx = MultiIndex.from_product((a, i), names=("Period", "CVR"))
|
| 580 |
+
df = DataFrame(
|
| 581 |
+
index=idx,
|
| 582 |
+
columns=(
|
| 583 |
+
"OMS",
|
| 584 |
+
"OMK",
|
| 585 |
+
"RES",
|
| 586 |
+
"DRIFT_IND",
|
| 587 |
+
"OEVRIG_IND",
|
| 588 |
+
"FIN_IND",
|
| 589 |
+
"VARE_UD",
|
| 590 |
+
"LOEN_UD",
|
| 591 |
+
"FIN_UD",
|
| 592 |
+
),
|
| 593 |
+
)
|
| 594 |
+
result = df.loc[("2013Q1", 1111), "OMS"]
|
| 595 |
+
|
| 596 |
+
alt = df.loc[(a[0], 1111), "OMS"]
|
| 597 |
+
assert np.isnan(alt)
|
| 598 |
+
|
| 599 |
+
# Because the resolution of the string matches, it is an exact lookup,
|
| 600 |
+
# not a slice
|
| 601 |
+
assert np.isnan(result)
|
| 602 |
+
|
| 603 |
+
# TODO: should it figure this out?
|
| 604 |
+
# alt = df.loc["2013Q1", 1111, "OMS"]
|
| 605 |
+
# assert np.isnan(alt)
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
def test_loc_datetime_mask_slicing():
|
| 609 |
+
# GH 16699
|
| 610 |
+
dt_idx = pd.to_datetime(["2017-05-04", "2017-05-05"])
|
| 611 |
+
m_idx = MultiIndex.from_product([dt_idx, dt_idx], names=["Idx1", "Idx2"])
|
| 612 |
+
df = DataFrame(
|
| 613 |
+
data=[[1, 2], [3, 4], [5, 6], [7, 6]], index=m_idx, columns=["C1", "C2"]
|
| 614 |
+
)
|
| 615 |
+
result = df.loc[(dt_idx[0], (df.index.get_level_values(1) > "2017-05-04")), "C1"]
|
| 616 |
+
expected = Series(
|
| 617 |
+
[3],
|
| 618 |
+
name="C1",
|
| 619 |
+
index=MultiIndex.from_tuples(
|
| 620 |
+
[(pd.Timestamp("2017-05-04"), pd.Timestamp("2017-05-05"))],
|
| 621 |
+
names=["Idx1", "Idx2"],
|
| 622 |
+
),
|
| 623 |
+
)
|
| 624 |
+
tm.assert_series_equal(result, expected)
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
def test_loc_datetime_series_tuple_slicing():
|
| 628 |
+
# https://github.com/pandas-dev/pandas/issues/35858
|
| 629 |
+
date = pd.Timestamp("2000")
|
| 630 |
+
ser = Series(
|
| 631 |
+
1,
|
| 632 |
+
index=MultiIndex.from_tuples([("a", date)], names=["a", "b"]),
|
| 633 |
+
name="c",
|
| 634 |
+
)
|
| 635 |
+
result = ser.loc[:, [date]]
|
| 636 |
+
tm.assert_series_equal(result, ser)
|
| 637 |
+
|
| 638 |
+
|
| 639 |
+
def test_loc_with_mi_indexer():
|
| 640 |
+
# https://github.com/pandas-dev/pandas/issues/35351
|
| 641 |
+
df = DataFrame(
|
| 642 |
+
data=[["a", 1], ["a", 0], ["b", 1], ["c", 2]],
|
| 643 |
+
index=MultiIndex.from_tuples(
|
| 644 |
+
[(0, 1), (1, 0), (1, 1), (1, 1)], names=["index", "date"]
|
| 645 |
+
),
|
| 646 |
+
columns=["author", "price"],
|
| 647 |
+
)
|
| 648 |
+
idx = MultiIndex.from_tuples([(0, 1), (1, 1)], names=["index", "date"])
|
| 649 |
+
result = df.loc[idx, :]
|
| 650 |
+
expected = DataFrame(
|
| 651 |
+
[["a", 1], ["b", 1], ["c", 2]],
|
| 652 |
+
index=MultiIndex.from_tuples([(0, 1), (1, 1), (1, 1)], names=["index", "date"]),
|
| 653 |
+
columns=["author", "price"],
|
| 654 |
+
)
|
| 655 |
+
tm.assert_frame_equal(result, expected)
|
| 656 |
+
|
| 657 |
+
|
| 658 |
+
def test_loc_mi_with_level1_named_0():
|
| 659 |
+
# GH#37194
|
| 660 |
+
dti = pd.date_range("2016-01-01", periods=3, tz="US/Pacific")
|
| 661 |
+
|
| 662 |
+
ser = Series(range(3), index=dti)
|
| 663 |
+
df = ser.to_frame()
|
| 664 |
+
df[1] = dti
|
| 665 |
+
|
| 666 |
+
df2 = df.set_index(0, append=True)
|
| 667 |
+
assert df2.index.names == (None, 0)
|
| 668 |
+
df2.index.get_loc(dti[0]) # smoke test
|
| 669 |
+
|
| 670 |
+
result = df2.loc[dti[0]]
|
| 671 |
+
expected = df2.iloc[[0]].droplevel(None)
|
| 672 |
+
tm.assert_frame_equal(result, expected)
|
| 673 |
+
|
| 674 |
+
ser2 = df2[1]
|
| 675 |
+
assert ser2.index.names == (None, 0)
|
| 676 |
+
|
| 677 |
+
result = ser2.loc[dti[0]]
|
| 678 |
+
expected = ser2.iloc[[0]].droplevel(None)
|
| 679 |
+
tm.assert_series_equal(result, expected)
|
| 680 |
+
|
| 681 |
+
|
| 682 |
+
def test_getitem_str_slice(datapath):
|
| 683 |
+
# GH#15928
|
| 684 |
+
path = datapath("reshape", "merge", "data", "quotes2.csv")
|
| 685 |
+
df = pd.read_csv(path, parse_dates=["time"])
|
| 686 |
+
df2 = df.set_index(["ticker", "time"]).sort_index()
|
| 687 |
+
|
| 688 |
+
res = df2.loc[("AAPL", slice("2016-05-25 13:30:00")), :].droplevel(0)
|
| 689 |
+
expected = df2.loc["AAPL"].loc[slice("2016-05-25 13:30:00"), :]
|
| 690 |
+
tm.assert_frame_equal(res, expected)
|
| 691 |
+
|
| 692 |
+
|
| 693 |
+
def test_3levels_leading_period_index():
|
| 694 |
+
# GH#24091
|
| 695 |
+
pi = pd.PeriodIndex(
|
| 696 |
+
["20181101 1100", "20181101 1200", "20181102 1300", "20181102 1400"],
|
| 697 |
+
name="datetime",
|
| 698 |
+
freq="B",
|
| 699 |
+
)
|
| 700 |
+
lev2 = ["A", "A", "Z", "W"]
|
| 701 |
+
lev3 = ["B", "C", "Q", "F"]
|
| 702 |
+
mi = MultiIndex.from_arrays([pi, lev2, lev3])
|
| 703 |
+
|
| 704 |
+
ser = Series(range(4), index=mi, dtype=np.float64)
|
| 705 |
+
result = ser.loc[(pi[0], "A", "B")]
|
| 706 |
+
assert result == 0.0
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
class TestKeyErrorsWithMultiIndex:
|
| 710 |
+
def test_missing_keys_raises_keyerror(self):
|
| 711 |
+
# GH#27420 KeyError, not TypeError
|
| 712 |
+
df = DataFrame(np.arange(12).reshape(4, 3), columns=["A", "B", "C"])
|
| 713 |
+
df2 = df.set_index(["A", "B"])
|
| 714 |
+
|
| 715 |
+
with pytest.raises(KeyError, match="1"):
|
| 716 |
+
df2.loc[(1, 6)]
|
| 717 |
+
|
| 718 |
+
def test_missing_key_raises_keyerror2(self):
|
| 719 |
+
# GH#21168 KeyError, not "IndexingError: Too many indexers"
|
| 720 |
+
ser = Series(-1, index=MultiIndex.from_product([[0, 1]] * 2))
|
| 721 |
+
|
| 722 |
+
with pytest.raises(KeyError, match=r"\(0, 3\)"):
|
| 723 |
+
ser.loc[0, 3]
|
| 724 |
+
|
| 725 |
+
def test_missing_key_combination(self):
|
| 726 |
+
# GH: 19556
|
| 727 |
+
mi = MultiIndex.from_arrays(
|
| 728 |
+
[
|
| 729 |
+
np.array(["a", "a", "b", "b"]),
|
| 730 |
+
np.array(["1", "2", "2", "3"]),
|
| 731 |
+
np.array(["c", "d", "c", "d"]),
|
| 732 |
+
],
|
| 733 |
+
names=["one", "two", "three"],
|
| 734 |
+
)
|
| 735 |
+
df = DataFrame(np.random.rand(4, 3), index=mi)
|
| 736 |
+
msg = r"\('b', '1', slice\(None, None, None\)\)"
|
| 737 |
+
with pytest.raises(KeyError, match=msg):
|
| 738 |
+
df.loc[("b", "1", slice(None)), :]
|
| 739 |
+
with pytest.raises(KeyError, match=msg):
|
| 740 |
+
df.index.get_locs(("b", "1", slice(None)))
|
| 741 |
+
with pytest.raises(KeyError, match=r"\('b', '1'\)"):
|
| 742 |
+
df.loc[("b", "1"), :]
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
def test_getitem_loc_commutability(multiindex_year_month_day_dataframe_random_data):
|
| 746 |
+
df = multiindex_year_month_day_dataframe_random_data
|
| 747 |
+
ser = df["A"]
|
| 748 |
+
result = ser[2000, 5]
|
| 749 |
+
expected = df.loc[2000, 5]["A"]
|
| 750 |
+
tm.assert_series_equal(result, expected)
|
| 751 |
+
|
| 752 |
+
|
| 753 |
+
def test_loc_with_nan():
|
| 754 |
+
# GH: 27104
|
| 755 |
+
df = DataFrame(
|
| 756 |
+
{"col": [1, 2, 5], "ind1": ["a", "d", np.nan], "ind2": [1, 4, 5]}
|
| 757 |
+
).set_index(["ind1", "ind2"])
|
| 758 |
+
result = df.loc[["a"]]
|
| 759 |
+
expected = DataFrame(
|
| 760 |
+
{"col": [1]}, index=MultiIndex.from_tuples([("a", 1)], names=["ind1", "ind2"])
|
| 761 |
+
)
|
| 762 |
+
tm.assert_frame_equal(result, expected)
|
| 763 |
+
|
| 764 |
+
result = df.loc["a"]
|
| 765 |
+
expected = DataFrame({"col": [1]}, index=Index([1], name="ind2"))
|
| 766 |
+
tm.assert_frame_equal(result, expected)
|
| 767 |
+
|
| 768 |
+
|
| 769 |
+
def test_getitem_non_found_tuple():
|
| 770 |
+
# GH: 25236
|
| 771 |
+
df = DataFrame([[1, 2, 3, 4]], columns=["a", "b", "c", "d"]).set_index(
|
| 772 |
+
["a", "b", "c"]
|
| 773 |
+
)
|
| 774 |
+
with pytest.raises(KeyError, match=r"\(2\.0, 2\.0, 3\.0\)"):
|
| 775 |
+
df.loc[(2.0, 2.0, 3.0)]
|
| 776 |
+
|
| 777 |
+
|
| 778 |
+
def test_get_loc_datetime_index():
|
| 779 |
+
# GH#24263
|
| 780 |
+
index = pd.date_range("2001-01-01", periods=100)
|
| 781 |
+
mi = MultiIndex.from_arrays([index])
|
| 782 |
+
# Check if get_loc matches for Index and MultiIndex
|
| 783 |
+
assert mi.get_loc("2001-01") == slice(0, 31, None)
|
| 784 |
+
assert index.get_loc("2001-01") == slice(0, 31, None)
|
| 785 |
+
|
| 786 |
+
loc = mi[::2].get_loc("2001-01")
|
| 787 |
+
expected = index[::2].get_loc("2001-01")
|
| 788 |
+
assert loc == expected
|
| 789 |
+
|
| 790 |
+
loc = mi.repeat(2).get_loc("2001-01")
|
| 791 |
+
expected = index.repeat(2).get_loc("2001-01")
|
| 792 |
+
assert loc == expected
|
| 793 |
+
|
| 794 |
+
loc = mi.append(mi).get_loc("2001-01")
|
| 795 |
+
expected = index.append(index).get_loc("2001-01")
|
| 796 |
+
# TODO: standardize return type for MultiIndex.get_loc
|
| 797 |
+
tm.assert_numpy_array_equal(loc.nonzero()[0], expected)
|
| 798 |
+
|
| 799 |
+
|
| 800 |
+
def test_loc_setitem_indexer_differently_ordered():
|
| 801 |
+
# GH#34603
|
| 802 |
+
mi = MultiIndex.from_product([["a", "b"], [0, 1]])
|
| 803 |
+
df = DataFrame([[1, 2], [3, 4], [5, 6], [7, 8]], index=mi)
|
| 804 |
+
|
| 805 |
+
indexer = ("a", [1, 0])
|
| 806 |
+
df.loc[indexer, :] = np.array([[9, 10], [11, 12]])
|
| 807 |
+
expected = DataFrame([[11, 12], [9, 10], [5, 6], [7, 8]], index=mi)
|
| 808 |
+
tm.assert_frame_equal(df, expected)
|
| 809 |
+
|
| 810 |
+
|
| 811 |
+
def test_loc_getitem_index_differently_ordered_slice_none():
|
| 812 |
+
# GH#31330
|
| 813 |
+
df = DataFrame(
|
| 814 |
+
[[1, 2], [3, 4], [5, 6], [7, 8]],
|
| 815 |
+
index=[["a", "a", "b", "b"], [1, 2, 1, 2]],
|
| 816 |
+
columns=["a", "b"],
|
| 817 |
+
)
|
| 818 |
+
result = df.loc[(slice(None), [2, 1]), :]
|
| 819 |
+
expected = DataFrame(
|
| 820 |
+
[[3, 4], [7, 8], [1, 2], [5, 6]],
|
| 821 |
+
index=[["a", "b", "a", "b"], [2, 2, 1, 1]],
|
| 822 |
+
columns=["a", "b"],
|
| 823 |
+
)
|
| 824 |
+
tm.assert_frame_equal(result, expected)
|
| 825 |
+
|
| 826 |
+
|
| 827 |
+
@pytest.mark.parametrize("indexer", [[1, 2, 7, 6, 2, 3, 8, 7], [1, 2, 7, 6, 3, 8]])
|
| 828 |
+
def test_loc_getitem_index_differently_ordered_slice_none_duplicates(indexer):
|
| 829 |
+
# GH#40978
|
| 830 |
+
df = DataFrame(
|
| 831 |
+
[1] * 8,
|
| 832 |
+
index=MultiIndex.from_tuples(
|
| 833 |
+
[(1, 1), (1, 2), (1, 7), (1, 6), (2, 2), (2, 3), (2, 8), (2, 7)]
|
| 834 |
+
),
|
| 835 |
+
columns=["a"],
|
| 836 |
+
)
|
| 837 |
+
result = df.loc[(slice(None), indexer), :]
|
| 838 |
+
expected = DataFrame(
|
| 839 |
+
[1] * 8,
|
| 840 |
+
index=[[1, 1, 2, 1, 2, 1, 2, 2], [1, 2, 2, 7, 7, 6, 3, 8]],
|
| 841 |
+
columns=["a"],
|
| 842 |
+
)
|
| 843 |
+
tm.assert_frame_equal(result, expected)
|
| 844 |
+
|
| 845 |
+
result = df.loc[df.index.isin(indexer, level=1), :]
|
| 846 |
+
tm.assert_frame_equal(result, df)
|
| 847 |
+
|
| 848 |
+
|
| 849 |
+
def test_loc_getitem_drops_levels_for_one_row_dataframe():
|
| 850 |
+
# GH#10521 "x" and "z" are both scalar indexing, so those levels are dropped
|
| 851 |
+
mi = MultiIndex.from_arrays([["x"], ["y"], ["z"]], names=["a", "b", "c"])
|
| 852 |
+
df = DataFrame({"d": [0]}, index=mi)
|
| 853 |
+
expected = df.droplevel([0, 2])
|
| 854 |
+
result = df.loc["x", :, "z"]
|
| 855 |
+
tm.assert_frame_equal(result, expected)
|
| 856 |
+
|
| 857 |
+
ser = Series([0], index=mi)
|
| 858 |
+
result = ser.loc["x", :, "z"]
|
| 859 |
+
expected = Series([0], index=Index(["y"], name="b"))
|
| 860 |
+
tm.assert_series_equal(result, expected)
|
| 861 |
+
|
| 862 |
+
|
| 863 |
+
def test_mi_columns_loc_list_label_order():
|
| 864 |
+
# GH 10710
|
| 865 |
+
cols = MultiIndex.from_product([["A", "B", "C"], [1, 2]])
|
| 866 |
+
df = DataFrame(np.zeros((5, 6)), columns=cols)
|
| 867 |
+
result = df.loc[:, ["B", "A"]]
|
| 868 |
+
expected = DataFrame(
|
| 869 |
+
np.zeros((5, 4)),
|
| 870 |
+
columns=MultiIndex.from_tuples([("B", 1), ("B", 2), ("A", 1), ("A", 2)]),
|
| 871 |
+
)
|
| 872 |
+
tm.assert_frame_equal(result, expected)
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
def test_mi_partial_indexing_list_raises():
|
| 876 |
+
# GH 13501
|
| 877 |
+
frame = DataFrame(
|
| 878 |
+
np.arange(12).reshape((4, 3)),
|
| 879 |
+
index=[["a", "a", "b", "b"], [1, 2, 1, 2]],
|
| 880 |
+
columns=[["Ohio", "Ohio", "Colorado"], ["Green", "Red", "Green"]],
|
| 881 |
+
)
|
| 882 |
+
frame.index.names = ["key1", "key2"]
|
| 883 |
+
frame.columns.names = ["state", "color"]
|
| 884 |
+
with pytest.raises(KeyError, match="\\[2\\] not in index"):
|
| 885 |
+
frame.loc[["b", 2], "Colorado"]
|
| 886 |
+
|
| 887 |
+
|
| 888 |
+
def test_mi_indexing_list_nonexistent_raises():
|
| 889 |
+
# GH 15452
|
| 890 |
+
s = Series(range(4), index=MultiIndex.from_product([[1, 2], ["a", "b"]]))
|
| 891 |
+
with pytest.raises(KeyError, match="\\['not' 'found'\\] not in index"):
|
| 892 |
+
s.loc[["not", "found"]]
|
| 893 |
+
|
| 894 |
+
|
| 895 |
+
def test_mi_add_cell_missing_row_non_unique():
|
| 896 |
+
# GH 16018
|
| 897 |
+
result = DataFrame(
|
| 898 |
+
[[1, 2, 5, 6], [3, 4, 7, 8]],
|
| 899 |
+
index=["a", "a"],
|
| 900 |
+
columns=MultiIndex.from_product([[1, 2], ["A", "B"]]),
|
| 901 |
+
)
|
| 902 |
+
result.loc["c"] = -1
|
| 903 |
+
result.loc["c", (1, "A")] = 3
|
| 904 |
+
result.loc["d", (1, "A")] = 3
|
| 905 |
+
expected = DataFrame(
|
| 906 |
+
[
|
| 907 |
+
[1.0, 2.0, 5.0, 6.0],
|
| 908 |
+
[3.0, 4.0, 7.0, 8.0],
|
| 909 |
+
[3.0, -1.0, -1, -1],
|
| 910 |
+
[3.0, np.nan, np.nan, np.nan],
|
| 911 |
+
],
|
| 912 |
+
index=["a", "a", "c", "d"],
|
| 913 |
+
columns=MultiIndex.from_product([[1, 2], ["A", "B"]]),
|
| 914 |
+
)
|
| 915 |
+
tm.assert_frame_equal(result, expected)
|
| 916 |
+
|
| 917 |
+
|
| 918 |
+
def test_loc_get_scalar_casting_to_float():
|
| 919 |
+
# GH#41369
|
| 920 |
+
df = DataFrame(
|
| 921 |
+
{"a": 1.0, "b": 2}, index=MultiIndex.from_arrays([[3], [4]], names=["c", "d"])
|
| 922 |
+
)
|
| 923 |
+
result = df.loc[(3, 4), "b"]
|
| 924 |
+
assert result == 2
|
| 925 |
+
assert isinstance(result, np.int64)
|
| 926 |
+
result = df.loc[[(3, 4)], "b"].iloc[0]
|
| 927 |
+
assert result == 2
|
| 928 |
+
assert isinstance(result, np.int64)
|
| 929 |
+
|
| 930 |
+
|
| 931 |
+
def test_loc_empty_single_selector_with_names():
|
| 932 |
+
# GH 19517
|
| 933 |
+
idx = MultiIndex.from_product([["a", "b"], ["A", "B"]], names=[1, 0])
|
| 934 |
+
s2 = Series(index=idx, dtype=np.float64)
|
| 935 |
+
result = s2.loc["a"]
|
| 936 |
+
expected = Series([np.nan, np.nan], index=Index(["A", "B"], name=0))
|
| 937 |
+
tm.assert_series_equal(result, expected)
|
| 938 |
+
|
| 939 |
+
|
| 940 |
+
def test_loc_keyerror_rightmost_key_missing():
|
| 941 |
+
# GH 20951
|
| 942 |
+
|
| 943 |
+
df = DataFrame(
|
| 944 |
+
{
|
| 945 |
+
"A": [100, 100, 200, 200, 300, 300],
|
| 946 |
+
"B": [10, 10, 20, 21, 31, 33],
|
| 947 |
+
"C": range(6),
|
| 948 |
+
}
|
| 949 |
+
)
|
| 950 |
+
df = df.set_index(["A", "B"])
|
| 951 |
+
with pytest.raises(KeyError, match="^1$"):
|
| 952 |
+
df.loc[(100, 1)]
|
| 953 |
+
|
| 954 |
+
|
| 955 |
+
def test_multindex_series_loc_with_tuple_label():
|
| 956 |
+
# GH#43908
|
| 957 |
+
mi = MultiIndex.from_tuples([(1, 2), (3, (4, 5))])
|
| 958 |
+
ser = Series([1, 2], index=mi)
|
| 959 |
+
result = ser.loc[(3, (4, 5))]
|
| 960 |
+
assert result == 2
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_multiindex.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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pytest
|
| 3 |
+
|
| 4 |
+
import pandas._libs.index as _index
|
| 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.rand(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 |
+
def test_indexing_over_hashtable_size_cutoff(self):
|
| 37 |
+
n = 10000
|
| 38 |
+
|
| 39 |
+
old_cutoff = _index._SIZE_CUTOFF
|
| 40 |
+
_index._SIZE_CUTOFF = 20000
|
| 41 |
+
|
| 42 |
+
s = Series(np.arange(n), MultiIndex.from_arrays((["a"] * n, np.arange(n))))
|
| 43 |
+
|
| 44 |
+
# hai it works!
|
| 45 |
+
assert s[("a", 5)] == 5
|
| 46 |
+
assert s[("a", 6)] == 6
|
| 47 |
+
assert s[("a", 7)] == 7
|
| 48 |
+
|
| 49 |
+
_index._SIZE_CUTOFF = old_cutoff
|
| 50 |
+
|
| 51 |
+
def test_multi_nan_indexing(self):
|
| 52 |
+
# GH 3588
|
| 53 |
+
df = DataFrame(
|
| 54 |
+
{
|
| 55 |
+
"a": ["R1", "R2", np.nan, "R4"],
|
| 56 |
+
"b": ["C1", "C2", "C3", "C4"],
|
| 57 |
+
"c": [10, 15, np.nan, 20],
|
| 58 |
+
}
|
| 59 |
+
)
|
| 60 |
+
result = df.set_index(["a", "b"], drop=False)
|
| 61 |
+
expected = DataFrame(
|
| 62 |
+
{
|
| 63 |
+
"a": ["R1", "R2", np.nan, "R4"],
|
| 64 |
+
"b": ["C1", "C2", "C3", "C4"],
|
| 65 |
+
"c": [10, 15, np.nan, 20],
|
| 66 |
+
},
|
| 67 |
+
index=[
|
| 68 |
+
Index(["R1", "R2", np.nan, "R4"], name="a"),
|
| 69 |
+
Index(["C1", "C2", "C3", "C4"], name="b"),
|
| 70 |
+
],
|
| 71 |
+
)
|
| 72 |
+
tm.assert_frame_equal(result, expected)
|
| 73 |
+
|
| 74 |
+
def test_exclusive_nat_column_indexing(self):
|
| 75 |
+
# GH 38025
|
| 76 |
+
# test multi indexing when one column exclusively contains NaT values
|
| 77 |
+
df = DataFrame(
|
| 78 |
+
{
|
| 79 |
+
"a": [pd.NaT, pd.NaT, pd.NaT, pd.NaT],
|
| 80 |
+
"b": ["C1", "C2", "C3", "C4"],
|
| 81 |
+
"c": [10, 15, np.nan, 20],
|
| 82 |
+
}
|
| 83 |
+
)
|
| 84 |
+
df = df.set_index(["a", "b"])
|
| 85 |
+
expected = DataFrame(
|
| 86 |
+
{
|
| 87 |
+
"c": [10, 15, np.nan, 20],
|
| 88 |
+
},
|
| 89 |
+
index=[
|
| 90 |
+
Index([pd.NaT, pd.NaT, pd.NaT, pd.NaT], name="a"),
|
| 91 |
+
Index(["C1", "C2", "C3", "C4"], name="b"),
|
| 92 |
+
],
|
| 93 |
+
)
|
| 94 |
+
tm.assert_frame_equal(df, expected)
|
| 95 |
+
|
| 96 |
+
def test_nested_tuples_duplicates(self):
|
| 97 |
+
# GH#30892
|
| 98 |
+
|
| 99 |
+
dti = pd.to_datetime(["20190101", "20190101", "20190102"])
|
| 100 |
+
idx = Index(["a", "a", "c"])
|
| 101 |
+
mi = MultiIndex.from_arrays([dti, idx], names=["index1", "index2"])
|
| 102 |
+
|
| 103 |
+
df = DataFrame({"c1": [1, 2, 3], "c2": [np.nan, np.nan, np.nan]}, index=mi)
|
| 104 |
+
|
| 105 |
+
expected = DataFrame({"c1": df["c1"], "c2": [1.0, 1.0, np.nan]}, index=mi)
|
| 106 |
+
|
| 107 |
+
df2 = df.copy(deep=True)
|
| 108 |
+
df2.loc[(dti[0], "a"), "c2"] = 1.0
|
| 109 |
+
tm.assert_frame_equal(df2, expected)
|
| 110 |
+
|
| 111 |
+
df3 = df.copy(deep=True)
|
| 112 |
+
df3.loc[[(dti[0], "a")], "c2"] = 1.0
|
| 113 |
+
tm.assert_frame_equal(df3, expected)
|
| 114 |
+
|
| 115 |
+
def test_multiindex_with_datatime_level_preserves_freq(self):
|
| 116 |
+
# https://github.com/pandas-dev/pandas/issues/35563
|
| 117 |
+
idx = Index(range(2), name="A")
|
| 118 |
+
dti = pd.date_range("2020-01-01", periods=7, freq="D", name="B")
|
| 119 |
+
mi = MultiIndex.from_product([idx, dti])
|
| 120 |
+
df = DataFrame(np.random.randn(14, 2), index=mi)
|
| 121 |
+
result = df.loc[0].index
|
| 122 |
+
tm.assert_index_equal(result, dti)
|
| 123 |
+
assert result.freq == dti.freq
|
| 124 |
+
|
| 125 |
+
def test_multiindex_complex(self):
|
| 126 |
+
# GH#42145
|
| 127 |
+
complex_data = [1 + 2j, 4 - 3j, 10 - 1j]
|
| 128 |
+
non_complex_data = [3, 4, 5]
|
| 129 |
+
result = DataFrame(
|
| 130 |
+
{
|
| 131 |
+
"x": complex_data,
|
| 132 |
+
"y": non_complex_data,
|
| 133 |
+
"z": non_complex_data,
|
| 134 |
+
}
|
| 135 |
+
)
|
| 136 |
+
result.set_index(["x", "y"], inplace=True)
|
| 137 |
+
expected = DataFrame(
|
| 138 |
+
{"z": non_complex_data},
|
| 139 |
+
index=MultiIndex.from_arrays(
|
| 140 |
+
[complex_data, non_complex_data],
|
| 141 |
+
names=("x", "y"),
|
| 142 |
+
),
|
| 143 |
+
)
|
| 144 |
+
tm.assert_frame_equal(result, expected)
|
| 145 |
+
|
| 146 |
+
def test_rename_multiindex_with_duplicates(self):
|
| 147 |
+
# GH 38015
|
| 148 |
+
mi = MultiIndex.from_tuples([("A", "cat"), ("B", "cat"), ("B", "cat")])
|
| 149 |
+
df = DataFrame(index=mi)
|
| 150 |
+
df = df.rename(index={"A": "Apple"}, level=0)
|
| 151 |
+
|
| 152 |
+
mi2 = MultiIndex.from_tuples([("Apple", "cat"), ("B", "cat"), ("B", "cat")])
|
| 153 |
+
expected = DataFrame(index=mi2)
|
| 154 |
+
tm.assert_frame_equal(df, expected)
|
| 155 |
+
|
| 156 |
+
def test_series_align_multiindex_with_nan_overlap_only(self):
|
| 157 |
+
# GH 38439
|
| 158 |
+
mi1 = MultiIndex.from_arrays([[81.0, np.nan], [np.nan, np.nan]])
|
| 159 |
+
mi2 = MultiIndex.from_arrays([[np.nan, 82.0], [np.nan, np.nan]])
|
| 160 |
+
ser1 = Series([1, 2], index=mi1)
|
| 161 |
+
ser2 = Series([1, 2], index=mi2)
|
| 162 |
+
result1, result2 = ser1.align(ser2)
|
| 163 |
+
|
| 164 |
+
mi = MultiIndex.from_arrays([[81.0, 82.0, np.nan], [np.nan, np.nan, np.nan]])
|
| 165 |
+
expected1 = Series([1.0, np.nan, 2.0], index=mi)
|
| 166 |
+
expected2 = Series([np.nan, 2.0, 1.0], index=mi)
|
| 167 |
+
|
| 168 |
+
tm.assert_series_equal(result1, expected1)
|
| 169 |
+
tm.assert_series_equal(result2, expected2)
|
| 170 |
+
|
| 171 |
+
def test_series_align_multiindex_with_nan(self):
|
| 172 |
+
# GH 38439
|
| 173 |
+
mi1 = MultiIndex.from_arrays([[81.0, np.nan], [np.nan, np.nan]])
|
| 174 |
+
mi2 = MultiIndex.from_arrays([[np.nan, 81.0], [np.nan, np.nan]])
|
| 175 |
+
ser1 = Series([1, 2], index=mi1)
|
| 176 |
+
ser2 = Series([1, 2], index=mi2)
|
| 177 |
+
result1, result2 = ser1.align(ser2)
|
| 178 |
+
|
| 179 |
+
mi = MultiIndex.from_arrays([[81.0, np.nan], [np.nan, np.nan]])
|
| 180 |
+
expected1 = Series([1, 2], index=mi)
|
| 181 |
+
expected2 = Series([2, 1], index=mi)
|
| 182 |
+
|
| 183 |
+
tm.assert_series_equal(result1, expected1)
|
| 184 |
+
tm.assert_series_equal(result2, expected2)
|
| 185 |
+
|
| 186 |
+
def test_nunique_smoke(self):
|
| 187 |
+
# GH 34019
|
| 188 |
+
n = DataFrame([[1, 2], [1, 2]]).set_index([0, 1]).index.nunique()
|
| 189 |
+
assert n == 1
|
| 190 |
+
|
| 191 |
+
def test_multiindex_repeated_keys(self):
|
| 192 |
+
# GH19414
|
| 193 |
+
tm.assert_series_equal(
|
| 194 |
+
Series([1, 2], MultiIndex.from_arrays([["a", "b"]])).loc[
|
| 195 |
+
["a", "a", "b", "b"]
|
| 196 |
+
],
|
| 197 |
+
Series([1, 1, 2, 2], MultiIndex.from_arrays([["a", "a", "b", "b"]])),
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
def test_multiindex_with_na_missing_key(self):
|
| 201 |
+
# GH46173
|
| 202 |
+
df = DataFrame.from_dict(
|
| 203 |
+
{
|
| 204 |
+
("foo",): [1, 2, 3],
|
| 205 |
+
("bar",): [5, 6, 7],
|
| 206 |
+
(None,): [8, 9, 0],
|
| 207 |
+
}
|
| 208 |
+
)
|
| 209 |
+
with pytest.raises(KeyError, match="missing_key"):
|
| 210 |
+
df[[("missing_key",)]]
|
| 211 |
+
|
| 212 |
+
def test_multiindex_dtype_preservation(self):
|
| 213 |
+
# GH51261
|
| 214 |
+
columns = MultiIndex.from_tuples([("A", "B")], names=["lvl1", "lvl2"])
|
| 215 |
+
df = DataFrame(["value"], columns=columns).astype("category")
|
| 216 |
+
df_no_multiindex = df["A"]
|
| 217 |
+
assert isinstance(df_no_multiindex["B"].dtype, CategoricalDtype)
|
| 218 |
+
|
| 219 |
+
# geopandas 1763 analogue
|
| 220 |
+
df = DataFrame(
|
| 221 |
+
[[1, 0], [0, 1]],
|
| 222 |
+
columns=[
|
| 223 |
+
["foo", "foo"],
|
| 224 |
+
["location", "location"],
|
| 225 |
+
["x", "y"],
|
| 226 |
+
],
|
| 227 |
+
).assign(bools=Series([True, False], dtype="boolean"))
|
| 228 |
+
assert isinstance(df["bools"].dtype, BooleanDtype)
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_partial.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 10 |
+
to_datetime,
|
| 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(np.random.randn(8, 4), index=index, columns=list("abcd"))
|
| 69 |
+
|
| 70 |
+
result = df.xs(("foo", "one"))
|
| 71 |
+
expected = df.loc["foo", "one"]
|
| 72 |
+
tm.assert_frame_equal(result, expected)
|
| 73 |
+
|
| 74 |
+
def test_getitem_partial(self, multiindex_year_month_day_dataframe_random_data):
|
| 75 |
+
ymd = multiindex_year_month_day_dataframe_random_data
|
| 76 |
+
ymd = ymd.T
|
| 77 |
+
result = ymd[2000, 2]
|
| 78 |
+
|
| 79 |
+
expected = ymd.reindex(columns=ymd.columns[ymd.columns.codes[1] == 1])
|
| 80 |
+
expected.columns = expected.columns.droplevel(0).droplevel(0)
|
| 81 |
+
tm.assert_frame_equal(result, expected)
|
| 82 |
+
|
| 83 |
+
def test_fancy_slice_partial(
|
| 84 |
+
self,
|
| 85 |
+
multiindex_dataframe_random_data,
|
| 86 |
+
multiindex_year_month_day_dataframe_random_data,
|
| 87 |
+
):
|
| 88 |
+
frame = multiindex_dataframe_random_data
|
| 89 |
+
result = frame.loc["bar":"baz"]
|
| 90 |
+
expected = frame[3:7]
|
| 91 |
+
tm.assert_frame_equal(result, expected)
|
| 92 |
+
|
| 93 |
+
ymd = multiindex_year_month_day_dataframe_random_data
|
| 94 |
+
result = ymd.loc[(2000, 2):(2000, 4)]
|
| 95 |
+
lev = ymd.index.codes[1]
|
| 96 |
+
expected = ymd[(lev >= 1) & (lev <= 3)]
|
| 97 |
+
tm.assert_frame_equal(result, expected)
|
| 98 |
+
|
| 99 |
+
def test_getitem_partial_column_select(self):
|
| 100 |
+
idx = MultiIndex(
|
| 101 |
+
codes=[[0, 0, 0], [0, 1, 1], [1, 0, 1]],
|
| 102 |
+
levels=[["a", "b"], ["x", "y"], ["p", "q"]],
|
| 103 |
+
)
|
| 104 |
+
df = DataFrame(np.random.rand(3, 2), index=idx)
|
| 105 |
+
|
| 106 |
+
result = df.loc[("a", "y"), :]
|
| 107 |
+
expected = df.loc[("a", "y")]
|
| 108 |
+
tm.assert_frame_equal(result, expected)
|
| 109 |
+
|
| 110 |
+
result = df.loc[("a", "y"), [1, 0]]
|
| 111 |
+
expected = df.loc[("a", "y")][[1, 0]]
|
| 112 |
+
tm.assert_frame_equal(result, expected)
|
| 113 |
+
|
| 114 |
+
with pytest.raises(KeyError, match=r"\('a', 'foo'\)"):
|
| 115 |
+
df.loc[("a", "foo"), :]
|
| 116 |
+
|
| 117 |
+
# TODO(ArrayManager) rewrite test to not use .values
|
| 118 |
+
# exp.loc[2000, 4].values[:] select multiple columns -> .values is not a view
|
| 119 |
+
@td.skip_array_manager_invalid_test
|
| 120 |
+
def test_partial_set(
|
| 121 |
+
self, multiindex_year_month_day_dataframe_random_data, using_copy_on_write
|
| 122 |
+
):
|
| 123 |
+
# GH #397
|
| 124 |
+
ymd = multiindex_year_month_day_dataframe_random_data
|
| 125 |
+
df = ymd.copy()
|
| 126 |
+
exp = ymd.copy()
|
| 127 |
+
df.loc[2000, 4] = 0
|
| 128 |
+
exp.iloc[65:85] = 0
|
| 129 |
+
tm.assert_frame_equal(df, exp)
|
| 130 |
+
|
| 131 |
+
if using_copy_on_write:
|
| 132 |
+
with tm.raises_chained_assignment_error():
|
| 133 |
+
df["A"].loc[2000, 4] = 1
|
| 134 |
+
df.loc[(2000, 4), "A"] = 1
|
| 135 |
+
else:
|
| 136 |
+
df["A"].loc[2000, 4] = 1
|
| 137 |
+
exp.iloc[65:85, 0] = 1
|
| 138 |
+
tm.assert_frame_equal(df, exp)
|
| 139 |
+
|
| 140 |
+
df.loc[2000] = 5
|
| 141 |
+
exp.iloc[:100] = 5
|
| 142 |
+
tm.assert_frame_equal(df, exp)
|
| 143 |
+
|
| 144 |
+
# this works...for now
|
| 145 |
+
if using_copy_on_write:
|
| 146 |
+
with tm.raises_chained_assignment_error():
|
| 147 |
+
df["A"].iloc[14] = 5
|
| 148 |
+
df["A"].iloc[14] == exp["A"].iloc[14]
|
| 149 |
+
else:
|
| 150 |
+
df["A"].iloc[14] = 5
|
| 151 |
+
assert df["A"].iloc[14] == 5
|
| 152 |
+
|
| 153 |
+
@pytest.mark.parametrize("dtype", [int, float])
|
| 154 |
+
def test_getitem_intkey_leading_level(
|
| 155 |
+
self, multiindex_year_month_day_dataframe_random_data, dtype
|
| 156 |
+
):
|
| 157 |
+
# GH#33355 dont fall-back to positional when leading level is int
|
| 158 |
+
ymd = multiindex_year_month_day_dataframe_random_data
|
| 159 |
+
levels = ymd.index.levels
|
| 160 |
+
ymd.index = ymd.index.set_levels([levels[0].astype(dtype)] + levels[1:])
|
| 161 |
+
ser = ymd["A"]
|
| 162 |
+
mi = ser.index
|
| 163 |
+
assert isinstance(mi, MultiIndex)
|
| 164 |
+
if dtype is int:
|
| 165 |
+
assert mi.levels[0].dtype == np.int_
|
| 166 |
+
else:
|
| 167 |
+
assert mi.levels[0].dtype == np.float64
|
| 168 |
+
|
| 169 |
+
assert 14 not in mi.levels[0]
|
| 170 |
+
assert not mi.levels[0]._should_fallback_to_positional
|
| 171 |
+
assert not mi._should_fallback_to_positional
|
| 172 |
+
|
| 173 |
+
with pytest.raises(KeyError, match="14"):
|
| 174 |
+
ser[14]
|
| 175 |
+
|
| 176 |
+
# ---------------------------------------------------------------------
|
| 177 |
+
|
| 178 |
+
def test_setitem_multiple_partial(self, multiindex_dataframe_random_data):
|
| 179 |
+
frame = multiindex_dataframe_random_data
|
| 180 |
+
expected = frame.copy()
|
| 181 |
+
result = frame.copy()
|
| 182 |
+
result.loc[["foo", "bar"]] = 0
|
| 183 |
+
expected.loc["foo"] = 0
|
| 184 |
+
expected.loc["bar"] = 0
|
| 185 |
+
tm.assert_frame_equal(result, expected)
|
| 186 |
+
|
| 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["A"].copy()
|
| 195 |
+
result = frame["A"].copy()
|
| 196 |
+
result.loc[["foo", "bar"]] = 0
|
| 197 |
+
expected.loc["foo"] = 0
|
| 198 |
+
expected.loc["bar"] = 0
|
| 199 |
+
tm.assert_series_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 |
+
@pytest.mark.parametrize(
|
| 209 |
+
"indexer, exp_idx, exp_values",
|
| 210 |
+
[
|
| 211 |
+
(slice("2019-2", None), [to_datetime("2019-02-01")], [2, 3]),
|
| 212 |
+
(
|
| 213 |
+
slice(None, "2019-2"),
|
| 214 |
+
date_range("2019", periods=2, freq="MS"),
|
| 215 |
+
[0, 1, 2, 3],
|
| 216 |
+
),
|
| 217 |
+
],
|
| 218 |
+
)
|
| 219 |
+
def test_partial_getitem_loc_datetime(self, indexer, exp_idx, exp_values):
|
| 220 |
+
# GH: 25165
|
| 221 |
+
date_idx = date_range("2019", periods=2, freq="MS")
|
| 222 |
+
df = DataFrame(
|
| 223 |
+
list(range(4)),
|
| 224 |
+
index=MultiIndex.from_product([date_idx, [0, 1]], names=["x", "y"]),
|
| 225 |
+
)
|
| 226 |
+
expected = DataFrame(
|
| 227 |
+
exp_values,
|
| 228 |
+
index=MultiIndex.from_product([exp_idx, [0, 1]], names=["x", "y"]),
|
| 229 |
+
)
|
| 230 |
+
result = df[indexer]
|
| 231 |
+
tm.assert_frame_equal(result, expected)
|
| 232 |
+
result = df.loc[indexer]
|
| 233 |
+
tm.assert_frame_equal(result, expected)
|
| 234 |
+
|
| 235 |
+
result = df.loc(axis=0)[indexer]
|
| 236 |
+
tm.assert_frame_equal(result, expected)
|
| 237 |
+
|
| 238 |
+
result = df.loc[indexer, :]
|
| 239 |
+
tm.assert_frame_equal(result, expected)
|
| 240 |
+
|
| 241 |
+
df2 = df.swaplevel(0, 1).sort_index()
|
| 242 |
+
expected = expected.swaplevel(0, 1).sort_index()
|
| 243 |
+
|
| 244 |
+
result = df2.loc[:, indexer, :]
|
| 245 |
+
tm.assert_frame_equal(result, expected)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def test_loc_getitem_partial_both_axis():
|
| 249 |
+
# gh-12660
|
| 250 |
+
iterables = [["a", "b"], [2, 1]]
|
| 251 |
+
columns = MultiIndex.from_product(iterables, names=["col1", "col2"])
|
| 252 |
+
rows = MultiIndex.from_product(iterables, names=["row1", "row2"])
|
| 253 |
+
df = DataFrame(np.random.randn(4, 4), index=rows, columns=columns)
|
| 254 |
+
expected = df.iloc[:2, 2:].droplevel("row1").droplevel("col1", axis=1)
|
| 255 |
+
result = df.loc["a", "b"]
|
| 256 |
+
tm.assert_frame_equal(result, expected)
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_setitem.py
ADDED
|
@@ -0,0 +1,544 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
| 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 |
+
Timestamp,
|
| 13 |
+
date_range,
|
| 14 |
+
isna,
|
| 15 |
+
notna,
|
| 16 |
+
)
|
| 17 |
+
import pandas._testing as tm
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def assert_equal(a, b):
|
| 21 |
+
assert a == b
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class TestMultiIndexSetItem:
|
| 25 |
+
def check(self, target, indexers, value, compare_fn=assert_equal, expected=None):
|
| 26 |
+
target.loc[indexers] = value
|
| 27 |
+
result = target.loc[indexers]
|
| 28 |
+
if expected is None:
|
| 29 |
+
expected = value
|
| 30 |
+
compare_fn(result, expected)
|
| 31 |
+
|
| 32 |
+
def test_setitem_multiindex(self):
|
| 33 |
+
# GH#7190
|
| 34 |
+
cols = ["A", "w", "l", "a", "x", "X", "d", "profit"]
|
| 35 |
+
index = MultiIndex.from_product(
|
| 36 |
+
[np.arange(0, 100), np.arange(0, 80)], names=["time", "firm"]
|
| 37 |
+
)
|
| 38 |
+
t, n = 0, 2
|
| 39 |
+
|
| 40 |
+
df = DataFrame(
|
| 41 |
+
np.nan,
|
| 42 |
+
columns=cols,
|
| 43 |
+
index=index,
|
| 44 |
+
)
|
| 45 |
+
self.check(target=df, indexers=((t, n), "X"), value=0)
|
| 46 |
+
|
| 47 |
+
df = DataFrame(-999, columns=cols, index=index)
|
| 48 |
+
self.check(target=df, indexers=((t, n), "X"), value=1)
|
| 49 |
+
|
| 50 |
+
df = DataFrame(columns=cols, index=index)
|
| 51 |
+
self.check(target=df, indexers=((t, n), "X"), value=2)
|
| 52 |
+
|
| 53 |
+
# gh-7218: assigning with 0-dim arrays
|
| 54 |
+
df = DataFrame(-999, columns=cols, index=index)
|
| 55 |
+
self.check(
|
| 56 |
+
target=df,
|
| 57 |
+
indexers=((t, n), "X"),
|
| 58 |
+
value=np.array(3),
|
| 59 |
+
expected=3,
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
def test_setitem_multiindex2(self):
|
| 63 |
+
# GH#5206
|
| 64 |
+
df = DataFrame(
|
| 65 |
+
np.arange(25).reshape(5, 5), columns="A,B,C,D,E".split(","), dtype=float
|
| 66 |
+
)
|
| 67 |
+
df["F"] = 99
|
| 68 |
+
row_selection = df["A"] % 2 == 0
|
| 69 |
+
col_selection = ["B", "C"]
|
| 70 |
+
df.loc[row_selection, col_selection] = df["F"]
|
| 71 |
+
output = DataFrame(99.0, index=[0, 2, 4], columns=["B", "C"])
|
| 72 |
+
tm.assert_frame_equal(df.loc[row_selection, col_selection], output)
|
| 73 |
+
self.check(
|
| 74 |
+
target=df,
|
| 75 |
+
indexers=(row_selection, col_selection),
|
| 76 |
+
value=df["F"],
|
| 77 |
+
compare_fn=tm.assert_frame_equal,
|
| 78 |
+
expected=output,
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
def test_setitem_multiindex3(self):
|
| 82 |
+
# GH#11372
|
| 83 |
+
idx = MultiIndex.from_product(
|
| 84 |
+
[["A", "B", "C"], date_range("2015-01-01", "2015-04-01", freq="MS")]
|
| 85 |
+
)
|
| 86 |
+
cols = MultiIndex.from_product(
|
| 87 |
+
[["foo", "bar"], date_range("2016-01-01", "2016-02-01", freq="MS")]
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
df = DataFrame(np.random.random((12, 4)), index=idx, columns=cols)
|
| 91 |
+
|
| 92 |
+
subidx = MultiIndex.from_tuples(
|
| 93 |
+
[("A", Timestamp("2015-01-01")), ("A", Timestamp("2015-02-01"))]
|
| 94 |
+
)
|
| 95 |
+
subcols = MultiIndex.from_tuples(
|
| 96 |
+
[("foo", Timestamp("2016-01-01")), ("foo", Timestamp("2016-02-01"))]
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
vals = DataFrame(np.random.random((2, 2)), index=subidx, columns=subcols)
|
| 100 |
+
self.check(
|
| 101 |
+
target=df,
|
| 102 |
+
indexers=(subidx, subcols),
|
| 103 |
+
value=vals,
|
| 104 |
+
compare_fn=tm.assert_frame_equal,
|
| 105 |
+
)
|
| 106 |
+
# set all columns
|
| 107 |
+
vals = DataFrame(np.random.random((2, 4)), index=subidx, columns=cols)
|
| 108 |
+
self.check(
|
| 109 |
+
target=df,
|
| 110 |
+
indexers=(subidx, slice(None, None, None)),
|
| 111 |
+
value=vals,
|
| 112 |
+
compare_fn=tm.assert_frame_equal,
|
| 113 |
+
)
|
| 114 |
+
# identity
|
| 115 |
+
copy = df.copy()
|
| 116 |
+
self.check(
|
| 117 |
+
target=df,
|
| 118 |
+
indexers=(df.index, df.columns),
|
| 119 |
+
value=df,
|
| 120 |
+
compare_fn=tm.assert_frame_equal,
|
| 121 |
+
expected=copy,
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
# TODO(ArrayManager) df.loc["bar"] *= 2 doesn't raise an error but results in
|
| 125 |
+
# all NaNs -> doesn't work in the "split" path (also for BlockManager actually)
|
| 126 |
+
@td.skip_array_manager_not_yet_implemented
|
| 127 |
+
def test_multiindex_setitem(self):
|
| 128 |
+
# GH 3738
|
| 129 |
+
# setting with a multi-index right hand side
|
| 130 |
+
arrays = [
|
| 131 |
+
np.array(["bar", "bar", "baz", "qux", "qux", "bar"]),
|
| 132 |
+
np.array(["one", "two", "one", "one", "two", "one"]),
|
| 133 |
+
np.arange(0, 6, 1),
|
| 134 |
+
]
|
| 135 |
+
|
| 136 |
+
df_orig = DataFrame(
|
| 137 |
+
np.random.randn(6, 3), index=arrays, columns=["A", "B", "C"]
|
| 138 |
+
).sort_index()
|
| 139 |
+
|
| 140 |
+
expected = df_orig.loc[["bar"]] * 2
|
| 141 |
+
df = df_orig.copy()
|
| 142 |
+
df.loc[["bar"]] *= 2
|
| 143 |
+
tm.assert_frame_equal(df.loc[["bar"]], expected)
|
| 144 |
+
|
| 145 |
+
# raise because these have differing levels
|
| 146 |
+
msg = "cannot align on a multi-index with out specifying the join levels"
|
| 147 |
+
with pytest.raises(TypeError, match=msg):
|
| 148 |
+
df.loc["bar"] *= 2
|
| 149 |
+
|
| 150 |
+
def test_multiindex_setitem2(self):
|
| 151 |
+
# from SO
|
| 152 |
+
# https://stackoverflow.com/questions/24572040/pandas-access-the-level-of-multiindex-for-inplace-operation
|
| 153 |
+
df_orig = DataFrame.from_dict(
|
| 154 |
+
{
|
| 155 |
+
"price": {
|
| 156 |
+
("DE", "Coal", "Stock"): 2,
|
| 157 |
+
("DE", "Gas", "Stock"): 4,
|
| 158 |
+
("DE", "Elec", "Demand"): 1,
|
| 159 |
+
("FR", "Gas", "Stock"): 5,
|
| 160 |
+
("FR", "Solar", "SupIm"): 0,
|
| 161 |
+
("FR", "Wind", "SupIm"): 0,
|
| 162 |
+
}
|
| 163 |
+
}
|
| 164 |
+
)
|
| 165 |
+
df_orig.index = MultiIndex.from_tuples(
|
| 166 |
+
df_orig.index, names=["Sit", "Com", "Type"]
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
expected = df_orig.copy()
|
| 170 |
+
expected.iloc[[0, 2, 3]] *= 2
|
| 171 |
+
|
| 172 |
+
idx = pd.IndexSlice
|
| 173 |
+
df = df_orig.copy()
|
| 174 |
+
df.loc[idx[:, :, "Stock"], :] *= 2
|
| 175 |
+
tm.assert_frame_equal(df, expected)
|
| 176 |
+
|
| 177 |
+
df = df_orig.copy()
|
| 178 |
+
df.loc[idx[:, :, "Stock"], "price"] *= 2
|
| 179 |
+
tm.assert_frame_equal(df, expected)
|
| 180 |
+
|
| 181 |
+
def test_multiindex_assignment(self):
|
| 182 |
+
# GH3777 part 2
|
| 183 |
+
|
| 184 |
+
# mixed dtype
|
| 185 |
+
df = DataFrame(
|
| 186 |
+
np.random.randint(5, 10, size=9).reshape(3, 3),
|
| 187 |
+
columns=list("abc"),
|
| 188 |
+
index=[[4, 4, 8], [8, 10, 12]],
|
| 189 |
+
)
|
| 190 |
+
df["d"] = np.nan
|
| 191 |
+
arr = np.array([0.0, 1.0])
|
| 192 |
+
|
| 193 |
+
df.loc[4, "d"] = arr
|
| 194 |
+
tm.assert_series_equal(df.loc[4, "d"], Series(arr, index=[8, 10], name="d"))
|
| 195 |
+
|
| 196 |
+
def test_multiindex_assignment_single_dtype(self, using_copy_on_write):
|
| 197 |
+
# GH3777 part 2b
|
| 198 |
+
# single dtype
|
| 199 |
+
arr = np.array([0.0, 1.0])
|
| 200 |
+
|
| 201 |
+
df = DataFrame(
|
| 202 |
+
np.random.randint(5, 10, size=9).reshape(3, 3),
|
| 203 |
+
columns=list("abc"),
|
| 204 |
+
index=[[4, 4, 8], [8, 10, 12]],
|
| 205 |
+
dtype=np.int64,
|
| 206 |
+
)
|
| 207 |
+
view = df["c"].iloc[:2].values
|
| 208 |
+
|
| 209 |
+
# arr can be losslessly cast to int, so this setitem is inplace
|
| 210 |
+
df.loc[4, "c"] = arr
|
| 211 |
+
exp = Series(arr, index=[8, 10], name="c", dtype="int64")
|
| 212 |
+
result = df.loc[4, "c"]
|
| 213 |
+
tm.assert_series_equal(result, exp)
|
| 214 |
+
|
| 215 |
+
# extra check for inplace-ness
|
| 216 |
+
if not using_copy_on_write:
|
| 217 |
+
tm.assert_numpy_array_equal(view, exp.values)
|
| 218 |
+
|
| 219 |
+
# arr + 0.5 cannot be cast losslessly to int, so we upcast
|
| 220 |
+
df.loc[4, "c"] = arr + 0.5
|
| 221 |
+
result = df.loc[4, "c"]
|
| 222 |
+
exp = exp + 0.5
|
| 223 |
+
tm.assert_series_equal(result, exp)
|
| 224 |
+
|
| 225 |
+
# scalar ok
|
| 226 |
+
df.loc[4, "c"] = 10
|
| 227 |
+
exp = Series(10, index=[8, 10], name="c", dtype="float64")
|
| 228 |
+
tm.assert_series_equal(df.loc[4, "c"], exp)
|
| 229 |
+
|
| 230 |
+
# invalid assignments
|
| 231 |
+
msg = "Must have equal len keys and value when setting with an iterable"
|
| 232 |
+
with pytest.raises(ValueError, match=msg):
|
| 233 |
+
df.loc[4, "c"] = [0, 1, 2, 3]
|
| 234 |
+
|
| 235 |
+
with pytest.raises(ValueError, match=msg):
|
| 236 |
+
df.loc[4, "c"] = [0]
|
| 237 |
+
|
| 238 |
+
# But with a length-1 listlike column indexer this behaves like
|
| 239 |
+
# `df.loc[4, "c"] = 0
|
| 240 |
+
df.loc[4, ["c"]] = [0]
|
| 241 |
+
assert (df.loc[4, "c"] == 0).all()
|
| 242 |
+
|
| 243 |
+
def test_groupby_example(self):
|
| 244 |
+
# groupby example
|
| 245 |
+
NUM_ROWS = 100
|
| 246 |
+
NUM_COLS = 10
|
| 247 |
+
col_names = ["A" + num for num in map(str, np.arange(NUM_COLS).tolist())]
|
| 248 |
+
index_cols = col_names[:5]
|
| 249 |
+
|
| 250 |
+
df = DataFrame(
|
| 251 |
+
np.random.randint(5, size=(NUM_ROWS, NUM_COLS)),
|
| 252 |
+
dtype=np.int64,
|
| 253 |
+
columns=col_names,
|
| 254 |
+
)
|
| 255 |
+
df = df.set_index(index_cols).sort_index()
|
| 256 |
+
grp = df.groupby(level=index_cols[:4])
|
| 257 |
+
df["new_col"] = np.nan
|
| 258 |
+
|
| 259 |
+
# we are actually operating on a copy here
|
| 260 |
+
# but in this case, that's ok
|
| 261 |
+
for name, df2 in grp:
|
| 262 |
+
new_vals = np.arange(df2.shape[0])
|
| 263 |
+
df.loc[name, "new_col"] = new_vals
|
| 264 |
+
|
| 265 |
+
def test_series_setitem(self, multiindex_year_month_day_dataframe_random_data):
|
| 266 |
+
ymd = multiindex_year_month_day_dataframe_random_data
|
| 267 |
+
s = ymd["A"]
|
| 268 |
+
|
| 269 |
+
s[2000, 3] = np.nan
|
| 270 |
+
assert isna(s.values[42:65]).all()
|
| 271 |
+
assert notna(s.values[:42]).all()
|
| 272 |
+
assert notna(s.values[65:]).all()
|
| 273 |
+
|
| 274 |
+
s[2000, 3, 10] = np.nan
|
| 275 |
+
assert isna(s.iloc[49])
|
| 276 |
+
|
| 277 |
+
with pytest.raises(KeyError, match="49"):
|
| 278 |
+
# GH#33355 dont fall-back to positional when leading level is int
|
| 279 |
+
s[49]
|
| 280 |
+
|
| 281 |
+
def test_frame_getitem_setitem_boolean(self, multiindex_dataframe_random_data):
|
| 282 |
+
frame = multiindex_dataframe_random_data
|
| 283 |
+
df = frame.T.copy()
|
| 284 |
+
values = df.values.copy()
|
| 285 |
+
|
| 286 |
+
result = df[df > 0]
|
| 287 |
+
expected = df.where(df > 0)
|
| 288 |
+
tm.assert_frame_equal(result, expected)
|
| 289 |
+
|
| 290 |
+
df[df > 0] = 5
|
| 291 |
+
values[values > 0] = 5
|
| 292 |
+
tm.assert_almost_equal(df.values, values)
|
| 293 |
+
|
| 294 |
+
df[df == 5] = 0
|
| 295 |
+
values[values == 5] = 0
|
| 296 |
+
tm.assert_almost_equal(df.values, values)
|
| 297 |
+
|
| 298 |
+
# a df that needs alignment first
|
| 299 |
+
df[df[:-1] < 0] = 2
|
| 300 |
+
np.putmask(values[:-1], values[:-1] < 0, 2)
|
| 301 |
+
tm.assert_almost_equal(df.values, values)
|
| 302 |
+
|
| 303 |
+
with pytest.raises(TypeError, match="boolean values only"):
|
| 304 |
+
df[df * 0] = 2
|
| 305 |
+
|
| 306 |
+
def test_frame_getitem_setitem_multislice(self):
|
| 307 |
+
levels = [["t1", "t2"], ["a", "b", "c"]]
|
| 308 |
+
codes = [[0, 0, 0, 1, 1], [0, 1, 2, 0, 1]]
|
| 309 |
+
midx = MultiIndex(codes=codes, levels=levels, names=[None, "id"])
|
| 310 |
+
df = DataFrame({"value": [1, 2, 3, 7, 8]}, index=midx)
|
| 311 |
+
|
| 312 |
+
result = df.loc[:, "value"]
|
| 313 |
+
tm.assert_series_equal(df["value"], result)
|
| 314 |
+
|
| 315 |
+
result = df.loc[df.index[1:3], "value"]
|
| 316 |
+
tm.assert_series_equal(df["value"][1:3], result)
|
| 317 |
+
|
| 318 |
+
result = df.loc[:, :]
|
| 319 |
+
tm.assert_frame_equal(df, result)
|
| 320 |
+
|
| 321 |
+
result = df
|
| 322 |
+
df.loc[:, "value"] = 10
|
| 323 |
+
result["value"] = 10
|
| 324 |
+
tm.assert_frame_equal(df, result)
|
| 325 |
+
|
| 326 |
+
df.loc[:, :] = 10
|
| 327 |
+
tm.assert_frame_equal(df, result)
|
| 328 |
+
|
| 329 |
+
def test_frame_setitem_multi_column(self):
|
| 330 |
+
df = DataFrame(
|
| 331 |
+
np.random.randn(10, 4), columns=[["a", "a", "b", "b"], [0, 1, 0, 1]]
|
| 332 |
+
)
|
| 333 |
+
|
| 334 |
+
cp = df.copy()
|
| 335 |
+
cp["a"] = cp["b"]
|
| 336 |
+
tm.assert_frame_equal(cp["a"], cp["b"])
|
| 337 |
+
|
| 338 |
+
# set with ndarray
|
| 339 |
+
cp = df.copy()
|
| 340 |
+
cp["a"] = cp["b"].values
|
| 341 |
+
tm.assert_frame_equal(cp["a"], cp["b"])
|
| 342 |
+
|
| 343 |
+
def test_frame_setitem_multi_column2(self):
|
| 344 |
+
# ---------------------------------------
|
| 345 |
+
# GH#1803
|
| 346 |
+
columns = MultiIndex.from_tuples([("A", "1"), ("A", "2"), ("B", "1")])
|
| 347 |
+
df = DataFrame(index=[1, 3, 5], columns=columns)
|
| 348 |
+
|
| 349 |
+
# Works, but adds a column instead of updating the two existing ones
|
| 350 |
+
df["A"] = 0.0 # Doesn't work
|
| 351 |
+
assert (df["A"].values == 0).all()
|
| 352 |
+
|
| 353 |
+
# it broadcasts
|
| 354 |
+
df["B", "1"] = [1, 2, 3]
|
| 355 |
+
df["A"] = df["B", "1"]
|
| 356 |
+
|
| 357 |
+
sliced_a1 = df["A", "1"]
|
| 358 |
+
sliced_a2 = df["A", "2"]
|
| 359 |
+
sliced_b1 = df["B", "1"]
|
| 360 |
+
tm.assert_series_equal(sliced_a1, sliced_b1, check_names=False)
|
| 361 |
+
tm.assert_series_equal(sliced_a2, sliced_b1, check_names=False)
|
| 362 |
+
assert sliced_a1.name == ("A", "1")
|
| 363 |
+
assert sliced_a2.name == ("A", "2")
|
| 364 |
+
assert sliced_b1.name == ("B", "1")
|
| 365 |
+
|
| 366 |
+
def test_loc_getitem_tuple_plus_columns(
|
| 367 |
+
self, multiindex_year_month_day_dataframe_random_data
|
| 368 |
+
):
|
| 369 |
+
# GH #1013
|
| 370 |
+
ymd = multiindex_year_month_day_dataframe_random_data
|
| 371 |
+
df = ymd[:5]
|
| 372 |
+
|
| 373 |
+
result = df.loc[(2000, 1, 6), ["A", "B", "C"]]
|
| 374 |
+
expected = df.loc[2000, 1, 6][["A", "B", "C"]]
|
| 375 |
+
tm.assert_series_equal(result, expected)
|
| 376 |
+
|
| 377 |
+
def test_loc_getitem_setitem_slice_integers(self, frame_or_series):
|
| 378 |
+
index = MultiIndex(
|
| 379 |
+
levels=[[0, 1, 2], [0, 2]], codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]]
|
| 380 |
+
)
|
| 381 |
+
|
| 382 |
+
obj = DataFrame(
|
| 383 |
+
np.random.randn(len(index), 4), index=index, columns=["a", "b", "c", "d"]
|
| 384 |
+
)
|
| 385 |
+
obj = tm.get_obj(obj, frame_or_series)
|
| 386 |
+
|
| 387 |
+
res = obj.loc[1:2]
|
| 388 |
+
exp = obj.reindex(obj.index[2:])
|
| 389 |
+
tm.assert_equal(res, exp)
|
| 390 |
+
|
| 391 |
+
obj.loc[1:2] = 7
|
| 392 |
+
assert (obj.loc[1:2] == 7).values.all()
|
| 393 |
+
|
| 394 |
+
def test_setitem_change_dtype(self, multiindex_dataframe_random_data):
|
| 395 |
+
frame = multiindex_dataframe_random_data
|
| 396 |
+
dft = frame.T
|
| 397 |
+
s = dft["foo", "two"]
|
| 398 |
+
dft["foo", "two"] = s > s.median()
|
| 399 |
+
tm.assert_series_equal(dft["foo", "two"], s > s.median())
|
| 400 |
+
# assert isinstance(dft._data.blocks[1].items, MultiIndex)
|
| 401 |
+
|
| 402 |
+
reindexed = dft.reindex(columns=[("foo", "two")])
|
| 403 |
+
tm.assert_series_equal(reindexed["foo", "two"], s > s.median())
|
| 404 |
+
|
| 405 |
+
def test_set_column_scalar_with_loc(
|
| 406 |
+
self, multiindex_dataframe_random_data, using_copy_on_write
|
| 407 |
+
):
|
| 408 |
+
frame = multiindex_dataframe_random_data
|
| 409 |
+
subset = frame.index[[1, 4, 5]]
|
| 410 |
+
|
| 411 |
+
frame.loc[subset] = 99
|
| 412 |
+
assert (frame.loc[subset].values == 99).all()
|
| 413 |
+
|
| 414 |
+
frame_original = frame.copy()
|
| 415 |
+
col = frame["B"]
|
| 416 |
+
col[subset] = 97
|
| 417 |
+
if using_copy_on_write:
|
| 418 |
+
# chained setitem doesn't work with CoW
|
| 419 |
+
tm.assert_frame_equal(frame, frame_original)
|
| 420 |
+
else:
|
| 421 |
+
assert (frame.loc[subset, "B"] == 97).all()
|
| 422 |
+
|
| 423 |
+
def test_nonunique_assignment_1750(self):
|
| 424 |
+
df = DataFrame(
|
| 425 |
+
[[1, 1, "x", "X"], [1, 1, "y", "Y"], [1, 2, "z", "Z"]], columns=list("ABCD")
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
+
df = df.set_index(["A", "B"])
|
| 429 |
+
mi = MultiIndex.from_tuples([(1, 1)])
|
| 430 |
+
|
| 431 |
+
df.loc[mi, "C"] = "_"
|
| 432 |
+
|
| 433 |
+
assert (df.xs((1, 1))["C"] == "_").all()
|
| 434 |
+
|
| 435 |
+
def test_astype_assignment_with_dups(self):
|
| 436 |
+
# GH 4686
|
| 437 |
+
# assignment with dups that has a dtype change
|
| 438 |
+
cols = MultiIndex.from_tuples([("A", "1"), ("B", "1"), ("A", "2")])
|
| 439 |
+
df = DataFrame(np.arange(3).reshape((1, 3)), columns=cols, dtype=object)
|
| 440 |
+
index = df.index.copy()
|
| 441 |
+
|
| 442 |
+
df["A"] = df["A"].astype(np.float64)
|
| 443 |
+
tm.assert_index_equal(df.index, index)
|
| 444 |
+
|
| 445 |
+
def test_setitem_nonmonotonic(self):
|
| 446 |
+
# https://github.com/pandas-dev/pandas/issues/31449
|
| 447 |
+
index = MultiIndex.from_tuples(
|
| 448 |
+
[("a", "c"), ("b", "x"), ("a", "d")], names=["l1", "l2"]
|
| 449 |
+
)
|
| 450 |
+
df = DataFrame(data=[0, 1, 2], index=index, columns=["e"])
|
| 451 |
+
df.loc["a", "e"] = np.arange(99, 101, dtype="int64")
|
| 452 |
+
expected = DataFrame({"e": [99, 1, 100]}, index=index)
|
| 453 |
+
tm.assert_frame_equal(df, expected)
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
class TestSetitemWithExpansionMultiIndex:
|
| 457 |
+
def test_setitem_new_column_mixed_depth(self):
|
| 458 |
+
arrays = [
|
| 459 |
+
["a", "top", "top", "routine1", "routine1", "routine2"],
|
| 460 |
+
["", "OD", "OD", "result1", "result2", "result1"],
|
| 461 |
+
["", "wx", "wy", "", "", ""],
|
| 462 |
+
]
|
| 463 |
+
|
| 464 |
+
tuples = sorted(zip(*arrays))
|
| 465 |
+
index = MultiIndex.from_tuples(tuples)
|
| 466 |
+
df = DataFrame(np.random.randn(4, 6), columns=index)
|
| 467 |
+
|
| 468 |
+
result = df.copy()
|
| 469 |
+
expected = df.copy()
|
| 470 |
+
result["b"] = [1, 2, 3, 4]
|
| 471 |
+
expected["b", "", ""] = [1, 2, 3, 4]
|
| 472 |
+
tm.assert_frame_equal(result, expected)
|
| 473 |
+
|
| 474 |
+
def test_setitem_new_column_all_na(self):
|
| 475 |
+
# GH#1534
|
| 476 |
+
mix = MultiIndex.from_tuples([("1a", "2a"), ("1a", "2b"), ("1a", "2c")])
|
| 477 |
+
df = DataFrame([[1, 2], [3, 4], [5, 6]], index=mix)
|
| 478 |
+
s = Series({(1, 1): 1, (1, 2): 2})
|
| 479 |
+
df["new"] = s
|
| 480 |
+
assert df["new"].isna().all()
|
| 481 |
+
|
| 482 |
+
def test_setitem_enlargement_keep_index_names(self):
|
| 483 |
+
# GH#53053
|
| 484 |
+
mi = MultiIndex.from_tuples([(1, 2, 3)], names=["i1", "i2", "i3"])
|
| 485 |
+
df = DataFrame(data=[[10, 20, 30]], index=mi, columns=["A", "B", "C"])
|
| 486 |
+
df.loc[(0, 0, 0)] = df.loc[(1, 2, 3)]
|
| 487 |
+
mi_expected = MultiIndex.from_tuples(
|
| 488 |
+
[(1, 2, 3), (0, 0, 0)], names=["i1", "i2", "i3"]
|
| 489 |
+
)
|
| 490 |
+
expected = DataFrame(
|
| 491 |
+
data=[[10, 20, 30], [10, 20, 30]],
|
| 492 |
+
index=mi_expected,
|
| 493 |
+
columns=["A", "B", "C"],
|
| 494 |
+
)
|
| 495 |
+
tm.assert_frame_equal(df, expected)
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
@td.skip_array_manager_invalid_test # df["foo"] select multiple columns -> .values
|
| 499 |
+
# is not a view
|
| 500 |
+
def test_frame_setitem_view_direct(
|
| 501 |
+
multiindex_dataframe_random_data, using_copy_on_write
|
| 502 |
+
):
|
| 503 |
+
# this works because we are modifying the underlying array
|
| 504 |
+
# really a no-no
|
| 505 |
+
df = multiindex_dataframe_random_data.T
|
| 506 |
+
if using_copy_on_write:
|
| 507 |
+
with pytest.raises(ValueError, match="read-only"):
|
| 508 |
+
df["foo"].values[:] = 0
|
| 509 |
+
assert (df["foo"].values != 0).all()
|
| 510 |
+
else:
|
| 511 |
+
df["foo"].values[:] = 0
|
| 512 |
+
assert (df["foo"].values == 0).all()
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
def test_frame_setitem_copy_raises(
|
| 516 |
+
multiindex_dataframe_random_data, using_copy_on_write
|
| 517 |
+
):
|
| 518 |
+
# will raise/warn as its chained assignment
|
| 519 |
+
df = multiindex_dataframe_random_data.T
|
| 520 |
+
if using_copy_on_write:
|
| 521 |
+
with tm.raises_chained_assignment_error():
|
| 522 |
+
df["foo"]["one"] = 2
|
| 523 |
+
else:
|
| 524 |
+
msg = "A value is trying to be set on a copy of a slice from a DataFrame"
|
| 525 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
| 526 |
+
df["foo"]["one"] = 2
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
def test_frame_setitem_copy_no_write(
|
| 530 |
+
multiindex_dataframe_random_data, using_copy_on_write
|
| 531 |
+
):
|
| 532 |
+
frame = multiindex_dataframe_random_data.T
|
| 533 |
+
expected = frame
|
| 534 |
+
df = frame.copy()
|
| 535 |
+
if using_copy_on_write:
|
| 536 |
+
with tm.raises_chained_assignment_error():
|
| 537 |
+
df["foo"]["one"] = 2
|
| 538 |
+
else:
|
| 539 |
+
msg = "A value is trying to be set on a copy of a slice from a DataFrame"
|
| 540 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
| 541 |
+
df["foo"]["one"] = 2
|
| 542 |
+
|
| 543 |
+
result = df
|
| 544 |
+
tm.assert_frame_equal(result, expected)
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/multiindex/test_slice.py
ADDED
|
@@ -0,0 +1,795 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
exp = ymd["A"].copy()
|
| 743 |
+
s[5:] = 0
|
| 744 |
+
exp.iloc[5:] = 0
|
| 745 |
+
tm.assert_numpy_array_equal(s.values, exp.values)
|
| 746 |
+
|
| 747 |
+
result = ymd[5:]
|
| 748 |
+
expected = ymd.reindex(s.index[5:])
|
| 749 |
+
tm.assert_frame_equal(result, expected)
|
| 750 |
+
|
| 751 |
+
@pytest.mark.parametrize(
|
| 752 |
+
"dtype, loc, iloc",
|
| 753 |
+
[
|
| 754 |
+
# dtype = int, step = -1
|
| 755 |
+
("int", slice(None, None, -1), slice(None, None, -1)),
|
| 756 |
+
("int", slice(3, None, -1), slice(3, None, -1)),
|
| 757 |
+
("int", slice(None, 1, -1), slice(None, 0, -1)),
|
| 758 |
+
("int", slice(3, 1, -1), slice(3, 0, -1)),
|
| 759 |
+
# dtype = int, step = -2
|
| 760 |
+
("int", slice(None, None, -2), slice(None, None, -2)),
|
| 761 |
+
("int", slice(3, None, -2), slice(3, None, -2)),
|
| 762 |
+
("int", slice(None, 1, -2), slice(None, 0, -2)),
|
| 763 |
+
("int", slice(3, 1, -2), slice(3, 0, -2)),
|
| 764 |
+
# dtype = str, step = -1
|
| 765 |
+
("str", slice(None, None, -1), slice(None, None, -1)),
|
| 766 |
+
("str", slice("d", None, -1), slice(3, None, -1)),
|
| 767 |
+
("str", slice(None, "b", -1), slice(None, 0, -1)),
|
| 768 |
+
("str", slice("d", "b", -1), slice(3, 0, -1)),
|
| 769 |
+
# dtype = str, step = -2
|
| 770 |
+
("str", slice(None, None, -2), slice(None, None, -2)),
|
| 771 |
+
("str", slice("d", None, -2), slice(3, None, -2)),
|
| 772 |
+
("str", slice(None, "b", -2), slice(None, 0, -2)),
|
| 773 |
+
("str", slice("d", "b", -2), slice(3, 0, -2)),
|
| 774 |
+
],
|
| 775 |
+
)
|
| 776 |
+
def test_loc_slice_negative_stepsize(self, dtype, loc, iloc):
|
| 777 |
+
# GH#38071
|
| 778 |
+
labels = {
|
| 779 |
+
"str": list("abcde"),
|
| 780 |
+
"int": range(5),
|
| 781 |
+
}[dtype]
|
| 782 |
+
|
| 783 |
+
mi = MultiIndex.from_arrays([labels] * 2)
|
| 784 |
+
df = DataFrame(1.0, index=mi, columns=["A"])
|
| 785 |
+
|
| 786 |
+
SLC = pd.IndexSlice
|
| 787 |
+
|
| 788 |
+
expected = df.iloc[iloc, :]
|
| 789 |
+
result_get_loc = df.loc[SLC[loc], :]
|
| 790 |
+
result_get_locs_level_0 = df.loc[SLC[loc, :], :]
|
| 791 |
+
result_get_locs_level_1 = df.loc[SLC[:, loc], :]
|
| 792 |
+
|
| 793 |
+
tm.assert_frame_equal(result_get_loc, expected)
|
| 794 |
+
tm.assert_frame_equal(result_get_locs_level_0, expected)
|
| 795 |
+
tm.assert_frame_equal(result_get_locs_level_1, expected)
|
videochat2/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.randn(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)
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/test_at.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import (
|
| 2 |
+
datetime,
|
| 3 |
+
timezone,
|
| 4 |
+
)
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pytest
|
| 8 |
+
|
| 9 |
+
from pandas.errors import InvalidIndexError
|
| 10 |
+
|
| 11 |
+
from pandas import (
|
| 12 |
+
CategoricalDtype,
|
| 13 |
+
CategoricalIndex,
|
| 14 |
+
DataFrame,
|
| 15 |
+
DatetimeIndex,
|
| 16 |
+
MultiIndex,
|
| 17 |
+
Series,
|
| 18 |
+
Timestamp,
|
| 19 |
+
)
|
| 20 |
+
import pandas._testing as tm
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_at_timezone():
|
| 24 |
+
# https://github.com/pandas-dev/pandas/issues/33544
|
| 25 |
+
result = DataFrame({"foo": [datetime(2000, 1, 1)]})
|
| 26 |
+
result.at[0, "foo"] = datetime(2000, 1, 2, tzinfo=timezone.utc)
|
| 27 |
+
expected = DataFrame(
|
| 28 |
+
{"foo": [datetime(2000, 1, 2, tzinfo=timezone.utc)]}, dtype=object
|
| 29 |
+
)
|
| 30 |
+
tm.assert_frame_equal(result, expected)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def test_selection_methods_of_assigned_col():
|
| 34 |
+
# GH 29282
|
| 35 |
+
df = DataFrame(data={"a": [1, 2, 3], "b": [4, 5, 6]})
|
| 36 |
+
df2 = DataFrame(data={"c": [7, 8, 9]}, index=[2, 1, 0])
|
| 37 |
+
df["c"] = df2["c"]
|
| 38 |
+
df.at[1, "c"] = 11
|
| 39 |
+
result = df
|
| 40 |
+
expected = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [9, 11, 7]})
|
| 41 |
+
tm.assert_frame_equal(result, expected)
|
| 42 |
+
result = df.at[1, "c"]
|
| 43 |
+
assert result == 11
|
| 44 |
+
|
| 45 |
+
result = df["c"]
|
| 46 |
+
expected = Series([9, 11, 7], name="c")
|
| 47 |
+
tm.assert_series_equal(result, expected)
|
| 48 |
+
|
| 49 |
+
result = df[["c"]]
|
| 50 |
+
expected = DataFrame({"c": [9, 11, 7]})
|
| 51 |
+
tm.assert_frame_equal(result, expected)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class TestAtSetItem:
|
| 55 |
+
def test_at_setitem_item_cache_cleared(self):
|
| 56 |
+
# GH#22372 Note the multi-step construction is necessary to trigger
|
| 57 |
+
# the original bug. pandas/issues/22372#issuecomment-413345309
|
| 58 |
+
df = DataFrame(index=[0])
|
| 59 |
+
df["x"] = 1
|
| 60 |
+
df["cost"] = 2
|
| 61 |
+
|
| 62 |
+
# accessing df["cost"] adds "cost" to the _item_cache
|
| 63 |
+
df["cost"]
|
| 64 |
+
|
| 65 |
+
# This loc[[0]] lookup used to call _consolidate_inplace at the
|
| 66 |
+
# BlockManager level, which failed to clear the _item_cache
|
| 67 |
+
df.loc[[0]]
|
| 68 |
+
|
| 69 |
+
df.at[0, "x"] = 4
|
| 70 |
+
df.at[0, "cost"] = 789
|
| 71 |
+
|
| 72 |
+
expected = DataFrame({"x": [4], "cost": 789}, index=[0])
|
| 73 |
+
tm.assert_frame_equal(df, expected)
|
| 74 |
+
|
| 75 |
+
# And in particular, check that the _item_cache has updated correctly.
|
| 76 |
+
tm.assert_series_equal(df["cost"], expected["cost"])
|
| 77 |
+
|
| 78 |
+
def test_at_setitem_mixed_index_assignment(self):
|
| 79 |
+
# GH#19860
|
| 80 |
+
ser = Series([1, 2, 3, 4, 5], index=["a", "b", "c", 1, 2])
|
| 81 |
+
ser.at["a"] = 11
|
| 82 |
+
assert ser.iat[0] == 11
|
| 83 |
+
ser.at[1] = 22
|
| 84 |
+
assert ser.iat[3] == 22
|
| 85 |
+
|
| 86 |
+
def test_at_setitem_categorical_missing(self):
|
| 87 |
+
df = DataFrame(
|
| 88 |
+
index=range(3), columns=range(3), dtype=CategoricalDtype(["foo", "bar"])
|
| 89 |
+
)
|
| 90 |
+
df.at[1, 1] = "foo"
|
| 91 |
+
|
| 92 |
+
expected = DataFrame(
|
| 93 |
+
[
|
| 94 |
+
[np.nan, np.nan, np.nan],
|
| 95 |
+
[np.nan, "foo", np.nan],
|
| 96 |
+
[np.nan, np.nan, np.nan],
|
| 97 |
+
],
|
| 98 |
+
dtype=CategoricalDtype(["foo", "bar"]),
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
tm.assert_frame_equal(df, expected)
|
| 102 |
+
|
| 103 |
+
def test_at_setitem_multiindex(self):
|
| 104 |
+
df = DataFrame(
|
| 105 |
+
np.zeros((3, 2), dtype="int64"),
|
| 106 |
+
columns=MultiIndex.from_tuples([("a", 0), ("a", 1)]),
|
| 107 |
+
)
|
| 108 |
+
df.at[0, "a"] = 10
|
| 109 |
+
expected = DataFrame(
|
| 110 |
+
[[10, 10], [0, 0], [0, 0]],
|
| 111 |
+
columns=MultiIndex.from_tuples([("a", 0), ("a", 1)]),
|
| 112 |
+
)
|
| 113 |
+
tm.assert_frame_equal(df, expected)
|
| 114 |
+
|
| 115 |
+
@pytest.mark.parametrize("row", (Timestamp("2019-01-01"), "2019-01-01"))
|
| 116 |
+
def test_at_datetime_index(self, row):
|
| 117 |
+
df = DataFrame(
|
| 118 |
+
data=[[1] * 2], index=DatetimeIndex(data=["2019-01-01", "2019-01-02"])
|
| 119 |
+
)
|
| 120 |
+
expected = DataFrame(
|
| 121 |
+
data=[[0.5, 1], [1.0, 1]],
|
| 122 |
+
index=DatetimeIndex(data=["2019-01-01", "2019-01-02"]),
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
df.at[row, 0] = 0.5
|
| 126 |
+
tm.assert_frame_equal(df, expected)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class TestAtSetItemWithExpansion:
|
| 130 |
+
def test_at_setitem_expansion_series_dt64tz_value(self, tz_naive_fixture):
|
| 131 |
+
# GH#25506
|
| 132 |
+
ts = Timestamp("2017-08-05 00:00:00+0100", tz=tz_naive_fixture)
|
| 133 |
+
result = Series(ts)
|
| 134 |
+
result.at[1] = ts
|
| 135 |
+
expected = Series([ts, ts])
|
| 136 |
+
tm.assert_series_equal(result, expected)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class TestAtWithDuplicates:
|
| 140 |
+
def test_at_with_duplicate_axes_requires_scalar_lookup(self):
|
| 141 |
+
# GH#33041 check that falling back to loc doesn't allow non-scalar
|
| 142 |
+
# args to slip in
|
| 143 |
+
|
| 144 |
+
arr = np.random.randn(6).reshape(3, 2)
|
| 145 |
+
df = DataFrame(arr, columns=["A", "A"])
|
| 146 |
+
|
| 147 |
+
msg = "Invalid call for scalar access"
|
| 148 |
+
with pytest.raises(ValueError, match=msg):
|
| 149 |
+
df.at[[1, 2]]
|
| 150 |
+
with pytest.raises(ValueError, match=msg):
|
| 151 |
+
df.at[1, ["A"]]
|
| 152 |
+
with pytest.raises(ValueError, match=msg):
|
| 153 |
+
df.at[:, "A"]
|
| 154 |
+
|
| 155 |
+
with pytest.raises(ValueError, match=msg):
|
| 156 |
+
df.at[[1, 2]] = 1
|
| 157 |
+
with pytest.raises(ValueError, match=msg):
|
| 158 |
+
df.at[1, ["A"]] = 1
|
| 159 |
+
with pytest.raises(ValueError, match=msg):
|
| 160 |
+
df.at[:, "A"] = 1
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class TestAtErrors:
|
| 164 |
+
# TODO: De-duplicate/parametrize
|
| 165 |
+
# test_at_series_raises_key_error2, test_at_frame_raises_key_error2
|
| 166 |
+
|
| 167 |
+
def test_at_series_raises_key_error(self, indexer_al):
|
| 168 |
+
# GH#31724 .at should match .loc
|
| 169 |
+
|
| 170 |
+
ser = Series([1, 2, 3], index=[3, 2, 1])
|
| 171 |
+
result = indexer_al(ser)[1]
|
| 172 |
+
assert result == 3
|
| 173 |
+
|
| 174 |
+
with pytest.raises(KeyError, match="a"):
|
| 175 |
+
indexer_al(ser)["a"]
|
| 176 |
+
|
| 177 |
+
def test_at_frame_raises_key_error(self, indexer_al):
|
| 178 |
+
# GH#31724 .at should match .loc
|
| 179 |
+
|
| 180 |
+
df = DataFrame({0: [1, 2, 3]}, index=[3, 2, 1])
|
| 181 |
+
|
| 182 |
+
result = indexer_al(df)[1, 0]
|
| 183 |
+
assert result == 3
|
| 184 |
+
|
| 185 |
+
with pytest.raises(KeyError, match="a"):
|
| 186 |
+
indexer_al(df)["a", 0]
|
| 187 |
+
|
| 188 |
+
with pytest.raises(KeyError, match="a"):
|
| 189 |
+
indexer_al(df)[1, "a"]
|
| 190 |
+
|
| 191 |
+
def test_at_series_raises_key_error2(self, indexer_al):
|
| 192 |
+
# at should not fallback
|
| 193 |
+
# GH#7814
|
| 194 |
+
# GH#31724 .at should match .loc
|
| 195 |
+
ser = Series([1, 2, 3], index=list("abc"))
|
| 196 |
+
result = indexer_al(ser)["a"]
|
| 197 |
+
assert result == 1
|
| 198 |
+
|
| 199 |
+
with pytest.raises(KeyError, match="^0$"):
|
| 200 |
+
indexer_al(ser)[0]
|
| 201 |
+
|
| 202 |
+
def test_at_frame_raises_key_error2(self, indexer_al):
|
| 203 |
+
# GH#31724 .at should match .loc
|
| 204 |
+
df = DataFrame({"A": [1, 2, 3]}, index=list("abc"))
|
| 205 |
+
result = indexer_al(df)["a", "A"]
|
| 206 |
+
assert result == 1
|
| 207 |
+
|
| 208 |
+
with pytest.raises(KeyError, match="^0$"):
|
| 209 |
+
indexer_al(df)["a", 0]
|
| 210 |
+
|
| 211 |
+
def test_at_frame_multiple_columns(self):
|
| 212 |
+
# GH#48296 - at shouldn't modify multiple columns
|
| 213 |
+
df = DataFrame({"a": [1, 2], "b": [3, 4]})
|
| 214 |
+
new_row = [6, 7]
|
| 215 |
+
with pytest.raises(
|
| 216 |
+
InvalidIndexError,
|
| 217 |
+
match=f"You can only assign a scalar value not a \\{type(new_row)}",
|
| 218 |
+
):
|
| 219 |
+
df.at[5] = new_row
|
| 220 |
+
|
| 221 |
+
def test_at_getitem_mixed_index_no_fallback(self):
|
| 222 |
+
# GH#19860
|
| 223 |
+
ser = Series([1, 2, 3, 4, 5], index=["a", "b", "c", 1, 2])
|
| 224 |
+
with pytest.raises(KeyError, match="^0$"):
|
| 225 |
+
ser.at[0]
|
| 226 |
+
with pytest.raises(KeyError, match="^4$"):
|
| 227 |
+
ser.at[4]
|
| 228 |
+
|
| 229 |
+
def test_at_categorical_integers(self):
|
| 230 |
+
# CategoricalIndex with integer categories that don't happen to match
|
| 231 |
+
# the Categorical's codes
|
| 232 |
+
ci = CategoricalIndex([3, 4])
|
| 233 |
+
|
| 234 |
+
arr = np.arange(4).reshape(2, 2)
|
| 235 |
+
frame = DataFrame(arr, index=ci)
|
| 236 |
+
|
| 237 |
+
for df in [frame, frame.T]:
|
| 238 |
+
for key in [0, 1]:
|
| 239 |
+
with pytest.raises(KeyError, match=str(key)):
|
| 240 |
+
df.at[key, key]
|
| 241 |
+
|
| 242 |
+
def test_at_applied_for_rows(self):
|
| 243 |
+
# GH#48729 .at should raise InvalidIndexError when assigning rows
|
| 244 |
+
df = DataFrame(index=["a"], columns=["col1", "col2"])
|
| 245 |
+
new_row = [123, 15]
|
| 246 |
+
with pytest.raises(
|
| 247 |
+
InvalidIndexError,
|
| 248 |
+
match=f"You can only assign a scalar value not a \\{type(new_row)}",
|
| 249 |
+
):
|
| 250 |
+
df.at["a"] = new_row
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/test_chaining_and_caching.py
ADDED
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from string import ascii_letters as letters
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from pandas.errors import (
|
| 7 |
+
SettingWithCopyError,
|
| 8 |
+
SettingWithCopyWarning,
|
| 9 |
+
)
|
| 10 |
+
import pandas.util._test_decorators as td
|
| 11 |
+
|
| 12 |
+
import pandas as pd
|
| 13 |
+
from pandas import (
|
| 14 |
+
DataFrame,
|
| 15 |
+
Series,
|
| 16 |
+
Timestamp,
|
| 17 |
+
date_range,
|
| 18 |
+
option_context,
|
| 19 |
+
)
|
| 20 |
+
import pandas._testing as tm
|
| 21 |
+
|
| 22 |
+
msg = "A value is trying to be set on a copy of a slice from a DataFrame"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def random_text(nobs=100):
|
| 26 |
+
# Construct a DataFrame where each row is a random slice from 'letters'
|
| 27 |
+
idxs = np.random.randint(len(letters), size=(nobs, 2))
|
| 28 |
+
idxs.sort(axis=1)
|
| 29 |
+
strings = [letters[x[0] : x[1]] for x in idxs]
|
| 30 |
+
|
| 31 |
+
return DataFrame(strings, columns=["letters"])
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class TestCaching:
|
| 35 |
+
def test_slice_consolidate_invalidate_item_cache(self, using_copy_on_write):
|
| 36 |
+
# this is chained assignment, but will 'work'
|
| 37 |
+
with option_context("chained_assignment", None):
|
| 38 |
+
# #3970
|
| 39 |
+
df = DataFrame({"aa": np.arange(5), "bb": [2.2] * 5})
|
| 40 |
+
|
| 41 |
+
# Creates a second float block
|
| 42 |
+
df["cc"] = 0.0
|
| 43 |
+
|
| 44 |
+
# caches a reference to the 'bb' series
|
| 45 |
+
df["bb"]
|
| 46 |
+
|
| 47 |
+
# repr machinery triggers consolidation
|
| 48 |
+
repr(df)
|
| 49 |
+
|
| 50 |
+
# Assignment to wrong series
|
| 51 |
+
if using_copy_on_write:
|
| 52 |
+
with tm.raises_chained_assignment_error():
|
| 53 |
+
df["bb"].iloc[0] = 0.17
|
| 54 |
+
else:
|
| 55 |
+
df["bb"].iloc[0] = 0.17
|
| 56 |
+
df._clear_item_cache()
|
| 57 |
+
if not using_copy_on_write:
|
| 58 |
+
tm.assert_almost_equal(df["bb"][0], 0.17)
|
| 59 |
+
else:
|
| 60 |
+
# with ArrayManager, parent is not mutated with chained assignment
|
| 61 |
+
tm.assert_almost_equal(df["bb"][0], 2.2)
|
| 62 |
+
|
| 63 |
+
@pytest.mark.parametrize("do_ref", [True, False])
|
| 64 |
+
def test_setitem_cache_updating(self, do_ref):
|
| 65 |
+
# GH 5424
|
| 66 |
+
cont = ["one", "two", "three", "four", "five", "six", "seven"]
|
| 67 |
+
|
| 68 |
+
df = DataFrame({"a": cont, "b": cont[3:] + cont[:3], "c": np.arange(7)})
|
| 69 |
+
|
| 70 |
+
# ref the cache
|
| 71 |
+
if do_ref:
|
| 72 |
+
df.loc[0, "c"]
|
| 73 |
+
|
| 74 |
+
# set it
|
| 75 |
+
df.loc[7, "c"] = 1
|
| 76 |
+
|
| 77 |
+
assert df.loc[0, "c"] == 0.0
|
| 78 |
+
assert df.loc[7, "c"] == 1.0
|
| 79 |
+
|
| 80 |
+
def test_setitem_cache_updating_slices(self, using_copy_on_write):
|
| 81 |
+
# GH 7084
|
| 82 |
+
# not updating cache on series setting with slices
|
| 83 |
+
expected = DataFrame(
|
| 84 |
+
{"A": [600, 600, 600]}, index=date_range("5/7/2014", "5/9/2014")
|
| 85 |
+
)
|
| 86 |
+
out = DataFrame({"A": [0, 0, 0]}, index=date_range("5/7/2014", "5/9/2014"))
|
| 87 |
+
df = DataFrame({"C": ["A", "A", "A"], "D": [100, 200, 300]})
|
| 88 |
+
|
| 89 |
+
# loop through df to update out
|
| 90 |
+
six = Timestamp("5/7/2014")
|
| 91 |
+
eix = Timestamp("5/9/2014")
|
| 92 |
+
for ix, row in df.iterrows():
|
| 93 |
+
out.loc[six:eix, row["C"]] = out.loc[six:eix, row["C"]] + row["D"]
|
| 94 |
+
|
| 95 |
+
tm.assert_frame_equal(out, expected)
|
| 96 |
+
tm.assert_series_equal(out["A"], expected["A"])
|
| 97 |
+
|
| 98 |
+
# try via a chain indexing
|
| 99 |
+
# this actually works
|
| 100 |
+
out = DataFrame({"A": [0, 0, 0]}, index=date_range("5/7/2014", "5/9/2014"))
|
| 101 |
+
out_original = out.copy()
|
| 102 |
+
for ix, row in df.iterrows():
|
| 103 |
+
v = out[row["C"]][six:eix] + row["D"]
|
| 104 |
+
if using_copy_on_write:
|
| 105 |
+
with tm.raises_chained_assignment_error():
|
| 106 |
+
out[row["C"]][six:eix] = v
|
| 107 |
+
else:
|
| 108 |
+
out[row["C"]][six:eix] = v
|
| 109 |
+
|
| 110 |
+
if not using_copy_on_write:
|
| 111 |
+
tm.assert_frame_equal(out, expected)
|
| 112 |
+
tm.assert_series_equal(out["A"], expected["A"])
|
| 113 |
+
else:
|
| 114 |
+
tm.assert_frame_equal(out, out_original)
|
| 115 |
+
tm.assert_series_equal(out["A"], out_original["A"])
|
| 116 |
+
|
| 117 |
+
out = DataFrame({"A": [0, 0, 0]}, index=date_range("5/7/2014", "5/9/2014"))
|
| 118 |
+
for ix, row in df.iterrows():
|
| 119 |
+
out.loc[six:eix, row["C"]] += row["D"]
|
| 120 |
+
|
| 121 |
+
tm.assert_frame_equal(out, expected)
|
| 122 |
+
tm.assert_series_equal(out["A"], expected["A"])
|
| 123 |
+
|
| 124 |
+
def test_altering_series_clears_parent_cache(self, using_copy_on_write):
|
| 125 |
+
# GH #33675
|
| 126 |
+
df = DataFrame([[1, 2], [3, 4]], index=["a", "b"], columns=["A", "B"])
|
| 127 |
+
ser = df["A"]
|
| 128 |
+
|
| 129 |
+
if using_copy_on_write:
|
| 130 |
+
assert "A" not in df._item_cache
|
| 131 |
+
else:
|
| 132 |
+
assert "A" in df._item_cache
|
| 133 |
+
|
| 134 |
+
# Adding a new entry to ser swaps in a new array, so "A" needs to
|
| 135 |
+
# be removed from df._item_cache
|
| 136 |
+
ser["c"] = 5
|
| 137 |
+
assert len(ser) == 3
|
| 138 |
+
assert "A" not in df._item_cache
|
| 139 |
+
assert df["A"] is not ser
|
| 140 |
+
assert len(df["A"]) == 2
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
class TestChaining:
|
| 144 |
+
def test_setitem_chained_setfault(self, using_copy_on_write):
|
| 145 |
+
# GH6026
|
| 146 |
+
data = ["right", "left", "left", "left", "right", "left", "timeout"]
|
| 147 |
+
mdata = ["right", "left", "left", "left", "right", "left", "none"]
|
| 148 |
+
|
| 149 |
+
df = DataFrame({"response": np.array(data)})
|
| 150 |
+
mask = df.response == "timeout"
|
| 151 |
+
if using_copy_on_write:
|
| 152 |
+
with tm.raises_chained_assignment_error():
|
| 153 |
+
df.response[mask] = "none"
|
| 154 |
+
tm.assert_frame_equal(df, DataFrame({"response": data}))
|
| 155 |
+
else:
|
| 156 |
+
df.response[mask] = "none"
|
| 157 |
+
tm.assert_frame_equal(df, DataFrame({"response": mdata}))
|
| 158 |
+
|
| 159 |
+
recarray = np.rec.fromarrays([data], names=["response"])
|
| 160 |
+
df = DataFrame(recarray)
|
| 161 |
+
mask = df.response == "timeout"
|
| 162 |
+
if using_copy_on_write:
|
| 163 |
+
with tm.raises_chained_assignment_error():
|
| 164 |
+
df.response[mask] = "none"
|
| 165 |
+
tm.assert_frame_equal(df, DataFrame({"response": data}))
|
| 166 |
+
else:
|
| 167 |
+
df.response[mask] = "none"
|
| 168 |
+
tm.assert_frame_equal(df, DataFrame({"response": mdata}))
|
| 169 |
+
|
| 170 |
+
df = DataFrame({"response": data, "response1": data})
|
| 171 |
+
df_original = df.copy()
|
| 172 |
+
mask = df.response == "timeout"
|
| 173 |
+
if using_copy_on_write:
|
| 174 |
+
with tm.raises_chained_assignment_error():
|
| 175 |
+
df.response[mask] = "none"
|
| 176 |
+
tm.assert_frame_equal(df, df_original)
|
| 177 |
+
else:
|
| 178 |
+
df.response[mask] = "none"
|
| 179 |
+
tm.assert_frame_equal(df, DataFrame({"response": mdata, "response1": data}))
|
| 180 |
+
|
| 181 |
+
# GH 6056
|
| 182 |
+
expected = DataFrame({"A": [np.nan, "bar", "bah", "foo", "bar"]})
|
| 183 |
+
df = DataFrame({"A": np.array(["foo", "bar", "bah", "foo", "bar"])})
|
| 184 |
+
if using_copy_on_write:
|
| 185 |
+
with tm.raises_chained_assignment_error():
|
| 186 |
+
df["A"].iloc[0] = np.nan
|
| 187 |
+
expected = DataFrame({"A": ["foo", "bar", "bah", "foo", "bar"]})
|
| 188 |
+
else:
|
| 189 |
+
df["A"].iloc[0] = np.nan
|
| 190 |
+
expected = DataFrame({"A": [np.nan, "bar", "bah", "foo", "bar"]})
|
| 191 |
+
result = df.head()
|
| 192 |
+
tm.assert_frame_equal(result, expected)
|
| 193 |
+
|
| 194 |
+
df = DataFrame({"A": np.array(["foo", "bar", "bah", "foo", "bar"])})
|
| 195 |
+
if using_copy_on_write:
|
| 196 |
+
with tm.raises_chained_assignment_error():
|
| 197 |
+
df.A.iloc[0] = np.nan
|
| 198 |
+
else:
|
| 199 |
+
df.A.iloc[0] = np.nan
|
| 200 |
+
result = df.head()
|
| 201 |
+
tm.assert_frame_equal(result, expected)
|
| 202 |
+
|
| 203 |
+
@pytest.mark.arm_slow
|
| 204 |
+
def test_detect_chained_assignment(self, using_copy_on_write):
|
| 205 |
+
with option_context("chained_assignment", "raise"):
|
| 206 |
+
# work with the chain
|
| 207 |
+
expected = DataFrame([[-5, 1], [-6, 3]], columns=list("AB"))
|
| 208 |
+
df = DataFrame(
|
| 209 |
+
np.arange(4).reshape(2, 2), columns=list("AB"), dtype="int64"
|
| 210 |
+
)
|
| 211 |
+
df_original = df.copy()
|
| 212 |
+
assert df._is_copy is None
|
| 213 |
+
|
| 214 |
+
if using_copy_on_write:
|
| 215 |
+
with tm.raises_chained_assignment_error():
|
| 216 |
+
df["A"][0] = -5
|
| 217 |
+
with tm.raises_chained_assignment_error():
|
| 218 |
+
df["A"][1] = -6
|
| 219 |
+
tm.assert_frame_equal(df, df_original)
|
| 220 |
+
else:
|
| 221 |
+
df["A"][0] = -5
|
| 222 |
+
df["A"][1] = -6
|
| 223 |
+
tm.assert_frame_equal(df, expected)
|
| 224 |
+
|
| 225 |
+
@pytest.mark.arm_slow
|
| 226 |
+
def test_detect_chained_assignment_raises(
|
| 227 |
+
self, using_array_manager, using_copy_on_write
|
| 228 |
+
):
|
| 229 |
+
# test with the chaining
|
| 230 |
+
df = DataFrame(
|
| 231 |
+
{
|
| 232 |
+
"A": Series(range(2), dtype="int64"),
|
| 233 |
+
"B": np.array(np.arange(2, 4), dtype=np.float64),
|
| 234 |
+
}
|
| 235 |
+
)
|
| 236 |
+
df_original = df.copy()
|
| 237 |
+
assert df._is_copy is None
|
| 238 |
+
|
| 239 |
+
if using_copy_on_write:
|
| 240 |
+
with tm.raises_chained_assignment_error():
|
| 241 |
+
df["A"][0] = -5
|
| 242 |
+
with tm.raises_chained_assignment_error():
|
| 243 |
+
df["A"][1] = -6
|
| 244 |
+
tm.assert_frame_equal(df, df_original)
|
| 245 |
+
elif not using_array_manager:
|
| 246 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
| 247 |
+
df["A"][0] = -5
|
| 248 |
+
|
| 249 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
| 250 |
+
df["A"][1] = np.nan
|
| 251 |
+
|
| 252 |
+
assert df["A"]._is_copy is None
|
| 253 |
+
else:
|
| 254 |
+
# INFO(ArrayManager) for ArrayManager it doesn't matter that it's
|
| 255 |
+
# a mixed dataframe
|
| 256 |
+
df["A"][0] = -5
|
| 257 |
+
df["A"][1] = -6
|
| 258 |
+
expected = DataFrame([[-5, 2], [-6, 3]], columns=list("AB"))
|
| 259 |
+
expected["B"] = expected["B"].astype("float64")
|
| 260 |
+
tm.assert_frame_equal(df, expected)
|
| 261 |
+
|
| 262 |
+
@pytest.mark.arm_slow
|
| 263 |
+
def test_detect_chained_assignment_fails(self, using_copy_on_write):
|
| 264 |
+
# Using a copy (the chain), fails
|
| 265 |
+
df = DataFrame(
|
| 266 |
+
{
|
| 267 |
+
"A": Series(range(2), dtype="int64"),
|
| 268 |
+
"B": np.array(np.arange(2, 4), dtype=np.float64),
|
| 269 |
+
}
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
if using_copy_on_write:
|
| 273 |
+
with tm.raises_chained_assignment_error():
|
| 274 |
+
df.loc[0]["A"] = -5
|
| 275 |
+
else:
|
| 276 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
| 277 |
+
df.loc[0]["A"] = -5
|
| 278 |
+
|
| 279 |
+
@pytest.mark.arm_slow
|
| 280 |
+
def test_detect_chained_assignment_doc_example(self, using_copy_on_write):
|
| 281 |
+
# Doc example
|
| 282 |
+
df = DataFrame(
|
| 283 |
+
{
|
| 284 |
+
"a": ["one", "one", "two", "three", "two", "one", "six"],
|
| 285 |
+
"c": Series(range(7), dtype="int64"),
|
| 286 |
+
}
|
| 287 |
+
)
|
| 288 |
+
assert df._is_copy is None
|
| 289 |
+
|
| 290 |
+
if using_copy_on_write:
|
| 291 |
+
indexer = df.a.str.startswith("o")
|
| 292 |
+
with tm.raises_chained_assignment_error():
|
| 293 |
+
df[indexer]["c"] = 42
|
| 294 |
+
else:
|
| 295 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
| 296 |
+
indexer = df.a.str.startswith("o")
|
| 297 |
+
df[indexer]["c"] = 42
|
| 298 |
+
|
| 299 |
+
@pytest.mark.arm_slow
|
| 300 |
+
def test_detect_chained_assignment_object_dtype(
|
| 301 |
+
self, using_array_manager, using_copy_on_write
|
| 302 |
+
):
|
| 303 |
+
expected = DataFrame({"A": [111, "bbb", "ccc"], "B": [1, 2, 3]})
|
| 304 |
+
df = DataFrame({"A": ["aaa", "bbb", "ccc"], "B": [1, 2, 3]})
|
| 305 |
+
df_original = df.copy()
|
| 306 |
+
|
| 307 |
+
if not using_copy_on_write:
|
| 308 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
| 309 |
+
df.loc[0]["A"] = 111
|
| 310 |
+
|
| 311 |
+
if using_copy_on_write:
|
| 312 |
+
with tm.raises_chained_assignment_error():
|
| 313 |
+
df["A"][0] = 111
|
| 314 |
+
tm.assert_frame_equal(df, df_original)
|
| 315 |
+
elif not using_array_manager:
|
| 316 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
| 317 |
+
df["A"][0] = 111
|
| 318 |
+
|
| 319 |
+
df.loc[0, "A"] = 111
|
| 320 |
+
tm.assert_frame_equal(df, expected)
|
| 321 |
+
else:
|
| 322 |
+
# INFO(ArrayManager) for ArrayManager it doesn't matter that it's
|
| 323 |
+
# a mixed dataframe
|
| 324 |
+
df["A"][0] = 111
|
| 325 |
+
tm.assert_frame_equal(df, expected)
|
| 326 |
+
|
| 327 |
+
@pytest.mark.arm_slow
|
| 328 |
+
def test_detect_chained_assignment_is_copy_pickle(self):
|
| 329 |
+
# gh-5475: Make sure that is_copy is picked up reconstruction
|
| 330 |
+
df = DataFrame({"A": [1, 2]})
|
| 331 |
+
assert df._is_copy is None
|
| 332 |
+
|
| 333 |
+
with tm.ensure_clean("__tmp__pickle") as path:
|
| 334 |
+
df.to_pickle(path)
|
| 335 |
+
df2 = pd.read_pickle(path)
|
| 336 |
+
df2["B"] = df2["A"]
|
| 337 |
+
df2["B"] = df2["A"]
|
| 338 |
+
|
| 339 |
+
@pytest.mark.arm_slow
|
| 340 |
+
def test_detect_chained_assignment_setting_entire_column(self):
|
| 341 |
+
# gh-5597: a spurious raise as we are setting the entire column here
|
| 342 |
+
|
| 343 |
+
df = random_text(100000)
|
| 344 |
+
|
| 345 |
+
# Always a copy
|
| 346 |
+
x = df.iloc[[0, 1, 2]]
|
| 347 |
+
assert x._is_copy is not None
|
| 348 |
+
|
| 349 |
+
x = df.iloc[[0, 1, 2, 4]]
|
| 350 |
+
assert x._is_copy is not None
|
| 351 |
+
|
| 352 |
+
# Explicitly copy
|
| 353 |
+
indexer = df.letters.apply(lambda x: len(x) > 10)
|
| 354 |
+
df = df.loc[indexer].copy()
|
| 355 |
+
|
| 356 |
+
assert df._is_copy is None
|
| 357 |
+
df["letters"] = df["letters"].apply(str.lower)
|
| 358 |
+
|
| 359 |
+
@pytest.mark.arm_slow
|
| 360 |
+
def test_detect_chained_assignment_implicit_take(self):
|
| 361 |
+
# Implicitly take
|
| 362 |
+
df = random_text(100000)
|
| 363 |
+
indexer = df.letters.apply(lambda x: len(x) > 10)
|
| 364 |
+
df = df.loc[indexer]
|
| 365 |
+
|
| 366 |
+
assert df._is_copy is not None
|
| 367 |
+
df["letters"] = df["letters"].apply(str.lower)
|
| 368 |
+
|
| 369 |
+
@pytest.mark.arm_slow
|
| 370 |
+
def test_detect_chained_assignment_implicit_take2(self, using_copy_on_write):
|
| 371 |
+
if using_copy_on_write:
|
| 372 |
+
pytest.skip("_is_copy is not always set for CoW")
|
| 373 |
+
# Implicitly take 2
|
| 374 |
+
df = random_text(100000)
|
| 375 |
+
indexer = df.letters.apply(lambda x: len(x) > 10)
|
| 376 |
+
|
| 377 |
+
df = df.loc[indexer]
|
| 378 |
+
assert df._is_copy is not None
|
| 379 |
+
df.loc[:, "letters"] = df["letters"].apply(str.lower)
|
| 380 |
+
|
| 381 |
+
# with the enforcement of #45333 in 2.0, the .loc[:, letters] setting
|
| 382 |
+
# is inplace, so df._is_copy remains non-None.
|
| 383 |
+
assert df._is_copy is not None
|
| 384 |
+
|
| 385 |
+
df["letters"] = df["letters"].apply(str.lower)
|
| 386 |
+
assert df._is_copy is None
|
| 387 |
+
|
| 388 |
+
@pytest.mark.arm_slow
|
| 389 |
+
def test_detect_chained_assignment_str(self):
|
| 390 |
+
df = random_text(100000)
|
| 391 |
+
indexer = df.letters.apply(lambda x: len(x) > 10)
|
| 392 |
+
df.loc[indexer, "letters"] = df.loc[indexer, "letters"].apply(str.lower)
|
| 393 |
+
|
| 394 |
+
@pytest.mark.arm_slow
|
| 395 |
+
def test_detect_chained_assignment_is_copy(self):
|
| 396 |
+
# an identical take, so no copy
|
| 397 |
+
df = DataFrame({"a": [1]}).dropna()
|
| 398 |
+
assert df._is_copy is None
|
| 399 |
+
df["a"] += 1
|
| 400 |
+
|
| 401 |
+
@pytest.mark.arm_slow
|
| 402 |
+
def test_detect_chained_assignment_sorting(self):
|
| 403 |
+
df = DataFrame(np.random.randn(10, 4))
|
| 404 |
+
ser = df.iloc[:, 0].sort_values()
|
| 405 |
+
|
| 406 |
+
tm.assert_series_equal(ser, df.iloc[:, 0].sort_values())
|
| 407 |
+
tm.assert_series_equal(ser, df[0].sort_values())
|
| 408 |
+
|
| 409 |
+
@pytest.mark.arm_slow
|
| 410 |
+
def test_detect_chained_assignment_false_positives(self):
|
| 411 |
+
# see gh-6025: false positives
|
| 412 |
+
df = DataFrame({"column1": ["a", "a", "a"], "column2": [4, 8, 9]})
|
| 413 |
+
str(df)
|
| 414 |
+
|
| 415 |
+
df["column1"] = df["column1"] + "b"
|
| 416 |
+
str(df)
|
| 417 |
+
|
| 418 |
+
df = df[df["column2"] != 8]
|
| 419 |
+
str(df)
|
| 420 |
+
|
| 421 |
+
df["column1"] = df["column1"] + "c"
|
| 422 |
+
str(df)
|
| 423 |
+
|
| 424 |
+
@pytest.mark.arm_slow
|
| 425 |
+
def test_detect_chained_assignment_undefined_column(self, using_copy_on_write):
|
| 426 |
+
# from SO:
|
| 427 |
+
# https://stackoverflow.com/questions/24054495/potential-bug-setting-value-for-undefined-column-using-iloc
|
| 428 |
+
df = DataFrame(np.arange(0, 9), columns=["count"])
|
| 429 |
+
df["group"] = "b"
|
| 430 |
+
df_original = df.copy()
|
| 431 |
+
|
| 432 |
+
if using_copy_on_write:
|
| 433 |
+
with tm.raises_chained_assignment_error():
|
| 434 |
+
df.iloc[0:5]["group"] = "a"
|
| 435 |
+
tm.assert_frame_equal(df, df_original)
|
| 436 |
+
else:
|
| 437 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
| 438 |
+
df.iloc[0:5]["group"] = "a"
|
| 439 |
+
|
| 440 |
+
@pytest.mark.arm_slow
|
| 441 |
+
def test_detect_chained_assignment_changing_dtype(
|
| 442 |
+
self, using_array_manager, using_copy_on_write
|
| 443 |
+
):
|
| 444 |
+
# Mixed type setting but same dtype & changing dtype
|
| 445 |
+
df = DataFrame(
|
| 446 |
+
{
|
| 447 |
+
"A": date_range("20130101", periods=5),
|
| 448 |
+
"B": np.random.randn(5),
|
| 449 |
+
"C": np.arange(5, dtype="int64"),
|
| 450 |
+
"D": ["a", "b", "c", "d", "e"],
|
| 451 |
+
}
|
| 452 |
+
)
|
| 453 |
+
df_original = df.copy()
|
| 454 |
+
|
| 455 |
+
if using_copy_on_write:
|
| 456 |
+
with tm.raises_chained_assignment_error():
|
| 457 |
+
df.loc[2]["D"] = "foo"
|
| 458 |
+
with tm.raises_chained_assignment_error():
|
| 459 |
+
df.loc[2]["C"] = "foo"
|
| 460 |
+
with tm.raises_chained_assignment_error():
|
| 461 |
+
df["C"][2] = "foo"
|
| 462 |
+
tm.assert_frame_equal(df, df_original)
|
| 463 |
+
|
| 464 |
+
if not using_copy_on_write:
|
| 465 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
| 466 |
+
df.loc[2]["D"] = "foo"
|
| 467 |
+
|
| 468 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
| 469 |
+
df.loc[2]["C"] = "foo"
|
| 470 |
+
|
| 471 |
+
if not using_array_manager:
|
| 472 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
| 473 |
+
df["C"][2] = "foo"
|
| 474 |
+
else:
|
| 475 |
+
# INFO(ArrayManager) for ArrayManager it doesn't matter if it's
|
| 476 |
+
# changing the dtype or not
|
| 477 |
+
df["C"][2] = "foo"
|
| 478 |
+
assert df.loc[2, "C"] == "foo"
|
| 479 |
+
|
| 480 |
+
def test_setting_with_copy_bug(self, using_copy_on_write):
|
| 481 |
+
# operating on a copy
|
| 482 |
+
df = DataFrame(
|
| 483 |
+
{"a": list(range(4)), "b": list("ab.."), "c": ["a", "b", np.nan, "d"]}
|
| 484 |
+
)
|
| 485 |
+
df_original = df.copy()
|
| 486 |
+
mask = pd.isna(df.c)
|
| 487 |
+
|
| 488 |
+
if using_copy_on_write:
|
| 489 |
+
with tm.raises_chained_assignment_error():
|
| 490 |
+
df[["c"]][mask] = df[["b"]][mask]
|
| 491 |
+
tm.assert_frame_equal(df, df_original)
|
| 492 |
+
else:
|
| 493 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
| 494 |
+
df[["c"]][mask] = df[["b"]][mask]
|
| 495 |
+
|
| 496 |
+
def test_setting_with_copy_bug_no_warning(self):
|
| 497 |
+
# invalid warning as we are returning a new object
|
| 498 |
+
# GH 8730
|
| 499 |
+
df1 = DataFrame({"x": Series(["a", "b", "c"]), "y": Series(["d", "e", "f"])})
|
| 500 |
+
df2 = df1[["x"]]
|
| 501 |
+
|
| 502 |
+
# this should not raise
|
| 503 |
+
df2["y"] = ["g", "h", "i"]
|
| 504 |
+
|
| 505 |
+
def test_detect_chained_assignment_warnings_errors(self, using_copy_on_write):
|
| 506 |
+
df = DataFrame({"A": ["aaa", "bbb", "ccc"], "B": [1, 2, 3]})
|
| 507 |
+
if using_copy_on_write:
|
| 508 |
+
with tm.raises_chained_assignment_error():
|
| 509 |
+
df.loc[0]["A"] = 111
|
| 510 |
+
return
|
| 511 |
+
|
| 512 |
+
with option_context("chained_assignment", "warn"):
|
| 513 |
+
with tm.assert_produces_warning(SettingWithCopyWarning):
|
| 514 |
+
df.loc[0]["A"] = 111
|
| 515 |
+
|
| 516 |
+
with option_context("chained_assignment", "raise"):
|
| 517 |
+
with pytest.raises(SettingWithCopyError, match=msg):
|
| 518 |
+
df.loc[0]["A"] = 111
|
| 519 |
+
|
| 520 |
+
@pytest.mark.parametrize("rhs", [3, DataFrame({0: [1, 2, 3, 4]})])
|
| 521 |
+
def test_detect_chained_assignment_warning_stacklevel(
|
| 522 |
+
self, rhs, using_copy_on_write
|
| 523 |
+
):
|
| 524 |
+
# GH#42570
|
| 525 |
+
df = DataFrame(np.arange(25).reshape(5, 5))
|
| 526 |
+
df_original = df.copy()
|
| 527 |
+
chained = df.loc[:3]
|
| 528 |
+
with option_context("chained_assignment", "warn"):
|
| 529 |
+
if not using_copy_on_write:
|
| 530 |
+
with tm.assert_produces_warning(SettingWithCopyWarning) as t:
|
| 531 |
+
chained[2] = rhs
|
| 532 |
+
assert t[0].filename == __file__
|
| 533 |
+
else:
|
| 534 |
+
# INFO(CoW) no warning, and original dataframe not changed
|
| 535 |
+
with tm.assert_produces_warning(None):
|
| 536 |
+
chained[2] = rhs
|
| 537 |
+
tm.assert_frame_equal(df, df_original)
|
| 538 |
+
|
| 539 |
+
# TODO(ArrayManager) fast_xs with array-like scalars is not yet working
|
| 540 |
+
@td.skip_array_manager_not_yet_implemented
|
| 541 |
+
def test_chained_getitem_with_lists(self):
|
| 542 |
+
# GH6394
|
| 543 |
+
# Regression in chained getitem indexing with embedded list-like from
|
| 544 |
+
# 0.12
|
| 545 |
+
|
| 546 |
+
df = DataFrame({"A": 5 * [np.zeros(3)], "B": 5 * [np.ones(3)]})
|
| 547 |
+
expected = df["A"].iloc[2]
|
| 548 |
+
result = df.loc[2, "A"]
|
| 549 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 550 |
+
result2 = df.iloc[2]["A"]
|
| 551 |
+
tm.assert_numpy_array_equal(result2, expected)
|
| 552 |
+
result3 = df["A"].loc[2]
|
| 553 |
+
tm.assert_numpy_array_equal(result3, expected)
|
| 554 |
+
result4 = df["A"].iloc[2]
|
| 555 |
+
tm.assert_numpy_array_equal(result4, expected)
|
| 556 |
+
|
| 557 |
+
def test_cache_updating(self):
|
| 558 |
+
# GH 4939, make sure to update the cache on setitem
|
| 559 |
+
|
| 560 |
+
df = tm.makeDataFrame()
|
| 561 |
+
df["A"] # cache series
|
| 562 |
+
df.loc["Hello Friend"] = df.iloc[0]
|
| 563 |
+
assert "Hello Friend" in df["A"].index
|
| 564 |
+
assert "Hello Friend" in df["B"].index
|
| 565 |
+
|
| 566 |
+
def test_cache_updating2(self, using_copy_on_write):
|
| 567 |
+
# 10264
|
| 568 |
+
df = DataFrame(
|
| 569 |
+
np.zeros((5, 5), dtype="int64"),
|
| 570 |
+
columns=["a", "b", "c", "d", "e"],
|
| 571 |
+
index=range(5),
|
| 572 |
+
)
|
| 573 |
+
df["f"] = 0
|
| 574 |
+
df_orig = df.copy()
|
| 575 |
+
if using_copy_on_write:
|
| 576 |
+
with pytest.raises(ValueError, match="read-only"):
|
| 577 |
+
df.f.values[3] = 1
|
| 578 |
+
tm.assert_frame_equal(df, df_orig)
|
| 579 |
+
return
|
| 580 |
+
|
| 581 |
+
df.f.values[3] = 1
|
| 582 |
+
|
| 583 |
+
df.f.values[3] = 2
|
| 584 |
+
expected = DataFrame(
|
| 585 |
+
np.zeros((5, 6), dtype="int64"),
|
| 586 |
+
columns=["a", "b", "c", "d", "e", "f"],
|
| 587 |
+
index=range(5),
|
| 588 |
+
)
|
| 589 |
+
expected.at[3, "f"] = 2
|
| 590 |
+
tm.assert_frame_equal(df, expected)
|
| 591 |
+
expected = Series([0, 0, 0, 2, 0], name="f")
|
| 592 |
+
tm.assert_series_equal(df.f, expected)
|
| 593 |
+
|
| 594 |
+
def test_iloc_setitem_chained_assignment(self, using_copy_on_write):
|
| 595 |
+
# GH#3970
|
| 596 |
+
with option_context("chained_assignment", None):
|
| 597 |
+
df = DataFrame({"aa": range(5), "bb": [2.2] * 5})
|
| 598 |
+
df["cc"] = 0.0
|
| 599 |
+
|
| 600 |
+
ck = [True] * len(df)
|
| 601 |
+
|
| 602 |
+
if using_copy_on_write:
|
| 603 |
+
with tm.raises_chained_assignment_error():
|
| 604 |
+
df["bb"].iloc[0] = 0.13
|
| 605 |
+
else:
|
| 606 |
+
df["bb"].iloc[0] = 0.13
|
| 607 |
+
|
| 608 |
+
# GH#3970 this lookup used to break the chained setting to 0.15
|
| 609 |
+
df.iloc[ck]
|
| 610 |
+
|
| 611 |
+
if using_copy_on_write:
|
| 612 |
+
with tm.raises_chained_assignment_error():
|
| 613 |
+
df["bb"].iloc[0] = 0.15
|
| 614 |
+
else:
|
| 615 |
+
df["bb"].iloc[0] = 0.15
|
| 616 |
+
|
| 617 |
+
if not using_copy_on_write:
|
| 618 |
+
assert df["bb"].iloc[0] == 0.15
|
| 619 |
+
else:
|
| 620 |
+
assert df["bb"].iloc[0] == 2.2
|
| 621 |
+
|
| 622 |
+
def test_getitem_loc_assignment_slice_state(self, using_copy_on_write):
|
| 623 |
+
# GH 13569
|
| 624 |
+
df = DataFrame({"a": [10, 20, 30]})
|
| 625 |
+
if using_copy_on_write:
|
| 626 |
+
with tm.raises_chained_assignment_error():
|
| 627 |
+
df["a"].loc[4] = 40
|
| 628 |
+
else:
|
| 629 |
+
df["a"].loc[4] = 40
|
| 630 |
+
tm.assert_frame_equal(df, DataFrame({"a": [10, 20, 30]}))
|
| 631 |
+
tm.assert_series_equal(df["a"], Series([10, 20, 30], name="a"))
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/test_coercion.py
ADDED
|
@@ -0,0 +1,904 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from datetime import (
|
| 4 |
+
datetime,
|
| 5 |
+
timedelta,
|
| 6 |
+
)
|
| 7 |
+
import itertools
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pytest
|
| 11 |
+
|
| 12 |
+
from pandas.compat import (
|
| 13 |
+
IS64,
|
| 14 |
+
is_platform_windows,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
import pandas as pd
|
| 18 |
+
import pandas._testing as tm
|
| 19 |
+
|
| 20 |
+
###############################################################
|
| 21 |
+
# Index / Series common tests which may trigger dtype coercions
|
| 22 |
+
###############################################################
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@pytest.fixture(autouse=True, scope="class")
|
| 26 |
+
def check_comprehensiveness(request):
|
| 27 |
+
# Iterate over combination of dtype, method and klass
|
| 28 |
+
# and ensure that each are contained within a collected test
|
| 29 |
+
cls = request.cls
|
| 30 |
+
combos = itertools.product(cls.klasses, cls.dtypes, [cls.method])
|
| 31 |
+
|
| 32 |
+
def has_test(combo):
|
| 33 |
+
klass, dtype, method = combo
|
| 34 |
+
cls_funcs = request.node.session.items
|
| 35 |
+
return any(
|
| 36 |
+
klass in x.name and dtype in x.name and method in x.name for x in cls_funcs
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
opts = request.config.option
|
| 40 |
+
if opts.lf or opts.keyword:
|
| 41 |
+
# If we are running with "last-failed" or -k foo, we expect to only
|
| 42 |
+
# run a subset of tests.
|
| 43 |
+
yield
|
| 44 |
+
|
| 45 |
+
else:
|
| 46 |
+
for combo in combos:
|
| 47 |
+
if not has_test(combo):
|
| 48 |
+
raise AssertionError(
|
| 49 |
+
f"test method is not defined: {cls.__name__}, {combo}"
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
yield
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class CoercionBase:
|
| 56 |
+
klasses = ["index", "series"]
|
| 57 |
+
dtypes = [
|
| 58 |
+
"object",
|
| 59 |
+
"int64",
|
| 60 |
+
"float64",
|
| 61 |
+
"complex128",
|
| 62 |
+
"bool",
|
| 63 |
+
"datetime64",
|
| 64 |
+
"datetime64tz",
|
| 65 |
+
"timedelta64",
|
| 66 |
+
"period",
|
| 67 |
+
]
|
| 68 |
+
|
| 69 |
+
@property
|
| 70 |
+
def method(self):
|
| 71 |
+
raise NotImplementedError(self)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class TestSetitemCoercion(CoercionBase):
|
| 75 |
+
method = "setitem"
|
| 76 |
+
|
| 77 |
+
# disable comprehensiveness tests, as most of these have been moved to
|
| 78 |
+
# tests.series.indexing.test_setitem in SetitemCastingEquivalents subclasses.
|
| 79 |
+
klasses: list[str] = []
|
| 80 |
+
|
| 81 |
+
def test_setitem_series_no_coercion_from_values_list(self):
|
| 82 |
+
# GH35865 - int casted to str when internally calling np.array(ser.values)
|
| 83 |
+
ser = pd.Series(["a", 1])
|
| 84 |
+
ser[:] = list(ser.values)
|
| 85 |
+
|
| 86 |
+
expected = pd.Series(["a", 1])
|
| 87 |
+
|
| 88 |
+
tm.assert_series_equal(ser, expected)
|
| 89 |
+
|
| 90 |
+
def _assert_setitem_index_conversion(
|
| 91 |
+
self, original_series, loc_key, expected_index, expected_dtype
|
| 92 |
+
):
|
| 93 |
+
"""test index's coercion triggered by assign key"""
|
| 94 |
+
temp = original_series.copy()
|
| 95 |
+
# GH#33469 pre-2.0 with int loc_key and temp.index.dtype == np.float64
|
| 96 |
+
# `temp[loc_key] = 5` treated loc_key as positional
|
| 97 |
+
temp[loc_key] = 5
|
| 98 |
+
exp = pd.Series([1, 2, 3, 4, 5], index=expected_index)
|
| 99 |
+
tm.assert_series_equal(temp, exp)
|
| 100 |
+
# check dtype explicitly for sure
|
| 101 |
+
assert temp.index.dtype == expected_dtype
|
| 102 |
+
|
| 103 |
+
temp = original_series.copy()
|
| 104 |
+
temp.loc[loc_key] = 5
|
| 105 |
+
exp = pd.Series([1, 2, 3, 4, 5], index=expected_index)
|
| 106 |
+
tm.assert_series_equal(temp, exp)
|
| 107 |
+
# check dtype explicitly for sure
|
| 108 |
+
assert temp.index.dtype == expected_dtype
|
| 109 |
+
|
| 110 |
+
@pytest.mark.parametrize(
|
| 111 |
+
"val,exp_dtype", [("x", object), (5, IndexError), (1.1, object)]
|
| 112 |
+
)
|
| 113 |
+
def test_setitem_index_object(self, val, exp_dtype):
|
| 114 |
+
obj = pd.Series([1, 2, 3, 4], index=list("abcd"))
|
| 115 |
+
assert obj.index.dtype == object
|
| 116 |
+
|
| 117 |
+
if exp_dtype is IndexError:
|
| 118 |
+
temp = obj.copy()
|
| 119 |
+
msg = "index 5 is out of bounds for axis 0 with size 4"
|
| 120 |
+
with pytest.raises(exp_dtype, match=msg):
|
| 121 |
+
temp[5] = 5
|
| 122 |
+
else:
|
| 123 |
+
exp_index = pd.Index(list("abcd") + [val])
|
| 124 |
+
self._assert_setitem_index_conversion(obj, val, exp_index, exp_dtype)
|
| 125 |
+
|
| 126 |
+
@pytest.mark.parametrize(
|
| 127 |
+
"val,exp_dtype", [(5, np.int64), (1.1, np.float64), ("x", object)]
|
| 128 |
+
)
|
| 129 |
+
def test_setitem_index_int64(self, val, exp_dtype):
|
| 130 |
+
obj = pd.Series([1, 2, 3, 4])
|
| 131 |
+
assert obj.index.dtype == np.int64
|
| 132 |
+
|
| 133 |
+
exp_index = pd.Index([0, 1, 2, 3, val])
|
| 134 |
+
self._assert_setitem_index_conversion(obj, val, exp_index, exp_dtype)
|
| 135 |
+
|
| 136 |
+
@pytest.mark.parametrize(
|
| 137 |
+
"val,exp_dtype", [(5, np.float64), (5.1, np.float64), ("x", object)]
|
| 138 |
+
)
|
| 139 |
+
def test_setitem_index_float64(self, val, exp_dtype, request):
|
| 140 |
+
obj = pd.Series([1, 2, 3, 4], index=[1.1, 2.1, 3.1, 4.1])
|
| 141 |
+
assert obj.index.dtype == np.float64
|
| 142 |
+
|
| 143 |
+
exp_index = pd.Index([1.1, 2.1, 3.1, 4.1, val])
|
| 144 |
+
self._assert_setitem_index_conversion(obj, val, exp_index, exp_dtype)
|
| 145 |
+
|
| 146 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
| 147 |
+
def test_setitem_series_period(self):
|
| 148 |
+
raise NotImplementedError
|
| 149 |
+
|
| 150 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
| 151 |
+
def test_setitem_index_complex128(self):
|
| 152 |
+
raise NotImplementedError
|
| 153 |
+
|
| 154 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
| 155 |
+
def test_setitem_index_bool(self):
|
| 156 |
+
raise NotImplementedError
|
| 157 |
+
|
| 158 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
| 159 |
+
def test_setitem_index_datetime64(self):
|
| 160 |
+
raise NotImplementedError
|
| 161 |
+
|
| 162 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
| 163 |
+
def test_setitem_index_datetime64tz(self):
|
| 164 |
+
raise NotImplementedError
|
| 165 |
+
|
| 166 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
| 167 |
+
def test_setitem_index_timedelta64(self):
|
| 168 |
+
raise NotImplementedError
|
| 169 |
+
|
| 170 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
| 171 |
+
def test_setitem_index_period(self):
|
| 172 |
+
raise NotImplementedError
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
class TestInsertIndexCoercion(CoercionBase):
|
| 176 |
+
klasses = ["index"]
|
| 177 |
+
method = "insert"
|
| 178 |
+
|
| 179 |
+
def _assert_insert_conversion(self, original, value, expected, expected_dtype):
|
| 180 |
+
"""test coercion triggered by insert"""
|
| 181 |
+
target = original.copy()
|
| 182 |
+
res = target.insert(1, value)
|
| 183 |
+
tm.assert_index_equal(res, expected)
|
| 184 |
+
assert res.dtype == expected_dtype
|
| 185 |
+
|
| 186 |
+
@pytest.mark.parametrize(
|
| 187 |
+
"insert, coerced_val, coerced_dtype",
|
| 188 |
+
[
|
| 189 |
+
(1, 1, object),
|
| 190 |
+
(1.1, 1.1, object),
|
| 191 |
+
(False, False, object),
|
| 192 |
+
("x", "x", object),
|
| 193 |
+
],
|
| 194 |
+
)
|
| 195 |
+
def test_insert_index_object(self, insert, coerced_val, coerced_dtype):
|
| 196 |
+
obj = pd.Index(list("abcd"))
|
| 197 |
+
assert obj.dtype == object
|
| 198 |
+
|
| 199 |
+
exp = pd.Index(["a", coerced_val, "b", "c", "d"])
|
| 200 |
+
self._assert_insert_conversion(obj, insert, exp, coerced_dtype)
|
| 201 |
+
|
| 202 |
+
@pytest.mark.parametrize(
|
| 203 |
+
"insert, coerced_val, coerced_dtype",
|
| 204 |
+
[
|
| 205 |
+
(1, 1, None),
|
| 206 |
+
(1.1, 1.1, np.float64),
|
| 207 |
+
(False, False, object), # GH#36319
|
| 208 |
+
("x", "x", object),
|
| 209 |
+
],
|
| 210 |
+
)
|
| 211 |
+
def test_insert_int_index(
|
| 212 |
+
self, any_int_numpy_dtype, insert, coerced_val, coerced_dtype
|
| 213 |
+
):
|
| 214 |
+
dtype = any_int_numpy_dtype
|
| 215 |
+
obj = pd.Index([1, 2, 3, 4], dtype=dtype)
|
| 216 |
+
coerced_dtype = coerced_dtype if coerced_dtype is not None else dtype
|
| 217 |
+
|
| 218 |
+
exp = pd.Index([1, coerced_val, 2, 3, 4], dtype=coerced_dtype)
|
| 219 |
+
self._assert_insert_conversion(obj, insert, exp, coerced_dtype)
|
| 220 |
+
|
| 221 |
+
@pytest.mark.parametrize(
|
| 222 |
+
"insert, coerced_val, coerced_dtype",
|
| 223 |
+
[
|
| 224 |
+
(1, 1.0, None),
|
| 225 |
+
(1.1, 1.1, np.float64),
|
| 226 |
+
(False, False, object), # GH#36319
|
| 227 |
+
("x", "x", object),
|
| 228 |
+
],
|
| 229 |
+
)
|
| 230 |
+
def test_insert_float_index(
|
| 231 |
+
self, float_numpy_dtype, insert, coerced_val, coerced_dtype
|
| 232 |
+
):
|
| 233 |
+
dtype = float_numpy_dtype
|
| 234 |
+
obj = pd.Index([1.0, 2.0, 3.0, 4.0], dtype=dtype)
|
| 235 |
+
coerced_dtype = coerced_dtype if coerced_dtype is not None else dtype
|
| 236 |
+
|
| 237 |
+
exp = pd.Index([1.0, coerced_val, 2.0, 3.0, 4.0], dtype=coerced_dtype)
|
| 238 |
+
self._assert_insert_conversion(obj, insert, exp, coerced_dtype)
|
| 239 |
+
|
| 240 |
+
@pytest.mark.parametrize(
|
| 241 |
+
"fill_val,exp_dtype",
|
| 242 |
+
[
|
| 243 |
+
(pd.Timestamp("2012-01-01"), "datetime64[ns]"),
|
| 244 |
+
(pd.Timestamp("2012-01-01", tz="US/Eastern"), "datetime64[ns, US/Eastern]"),
|
| 245 |
+
],
|
| 246 |
+
ids=["datetime64", "datetime64tz"],
|
| 247 |
+
)
|
| 248 |
+
@pytest.mark.parametrize(
|
| 249 |
+
"insert_value",
|
| 250 |
+
[pd.Timestamp("2012-01-01"), pd.Timestamp("2012-01-01", tz="Asia/Tokyo"), 1],
|
| 251 |
+
)
|
| 252 |
+
def test_insert_index_datetimes(self, fill_val, exp_dtype, insert_value):
|
| 253 |
+
obj = pd.DatetimeIndex(
|
| 254 |
+
["2011-01-01", "2011-01-02", "2011-01-03", "2011-01-04"], tz=fill_val.tz
|
| 255 |
+
)
|
| 256 |
+
assert obj.dtype == exp_dtype
|
| 257 |
+
|
| 258 |
+
exp = pd.DatetimeIndex(
|
| 259 |
+
["2011-01-01", fill_val.date(), "2011-01-02", "2011-01-03", "2011-01-04"],
|
| 260 |
+
tz=fill_val.tz,
|
| 261 |
+
)
|
| 262 |
+
self._assert_insert_conversion(obj, fill_val, exp, exp_dtype)
|
| 263 |
+
|
| 264 |
+
if fill_val.tz:
|
| 265 |
+
# mismatched tzawareness
|
| 266 |
+
ts = pd.Timestamp("2012-01-01")
|
| 267 |
+
result = obj.insert(1, ts)
|
| 268 |
+
expected = obj.astype(object).insert(1, ts)
|
| 269 |
+
assert expected.dtype == object
|
| 270 |
+
tm.assert_index_equal(result, expected)
|
| 271 |
+
|
| 272 |
+
ts = pd.Timestamp("2012-01-01", tz="Asia/Tokyo")
|
| 273 |
+
result = obj.insert(1, ts)
|
| 274 |
+
# once deprecation is enforced:
|
| 275 |
+
expected = obj.insert(1, ts.tz_convert(obj.dtype.tz))
|
| 276 |
+
assert expected.dtype == obj.dtype
|
| 277 |
+
tm.assert_index_equal(result, expected)
|
| 278 |
+
|
| 279 |
+
else:
|
| 280 |
+
# mismatched tzawareness
|
| 281 |
+
ts = pd.Timestamp("2012-01-01", tz="Asia/Tokyo")
|
| 282 |
+
result = obj.insert(1, ts)
|
| 283 |
+
expected = obj.astype(object).insert(1, ts)
|
| 284 |
+
assert expected.dtype == object
|
| 285 |
+
tm.assert_index_equal(result, expected)
|
| 286 |
+
|
| 287 |
+
item = 1
|
| 288 |
+
result = obj.insert(1, item)
|
| 289 |
+
expected = obj.astype(object).insert(1, item)
|
| 290 |
+
assert expected[1] == item
|
| 291 |
+
assert expected.dtype == object
|
| 292 |
+
tm.assert_index_equal(result, expected)
|
| 293 |
+
|
| 294 |
+
def test_insert_index_timedelta64(self):
|
| 295 |
+
obj = pd.TimedeltaIndex(["1 day", "2 day", "3 day", "4 day"])
|
| 296 |
+
assert obj.dtype == "timedelta64[ns]"
|
| 297 |
+
|
| 298 |
+
# timedelta64 + timedelta64 => timedelta64
|
| 299 |
+
exp = pd.TimedeltaIndex(["1 day", "10 day", "2 day", "3 day", "4 day"])
|
| 300 |
+
self._assert_insert_conversion(
|
| 301 |
+
obj, pd.Timedelta("10 day"), exp, "timedelta64[ns]"
|
| 302 |
+
)
|
| 303 |
+
|
| 304 |
+
for item in [pd.Timestamp("2012-01-01"), 1]:
|
| 305 |
+
result = obj.insert(1, item)
|
| 306 |
+
expected = obj.astype(object).insert(1, item)
|
| 307 |
+
assert expected.dtype == object
|
| 308 |
+
tm.assert_index_equal(result, expected)
|
| 309 |
+
|
| 310 |
+
@pytest.mark.parametrize(
|
| 311 |
+
"insert, coerced_val, coerced_dtype",
|
| 312 |
+
[
|
| 313 |
+
(pd.Period("2012-01", freq="M"), "2012-01", "period[M]"),
|
| 314 |
+
(pd.Timestamp("2012-01-01"), pd.Timestamp("2012-01-01"), object),
|
| 315 |
+
(1, 1, object),
|
| 316 |
+
("x", "x", object),
|
| 317 |
+
],
|
| 318 |
+
)
|
| 319 |
+
def test_insert_index_period(self, insert, coerced_val, coerced_dtype):
|
| 320 |
+
obj = pd.PeriodIndex(["2011-01", "2011-02", "2011-03", "2011-04"], freq="M")
|
| 321 |
+
assert obj.dtype == "period[M]"
|
| 322 |
+
|
| 323 |
+
data = [
|
| 324 |
+
pd.Period("2011-01", freq="M"),
|
| 325 |
+
coerced_val,
|
| 326 |
+
pd.Period("2011-02", freq="M"),
|
| 327 |
+
pd.Period("2011-03", freq="M"),
|
| 328 |
+
pd.Period("2011-04", freq="M"),
|
| 329 |
+
]
|
| 330 |
+
if isinstance(insert, pd.Period):
|
| 331 |
+
exp = pd.PeriodIndex(data, freq="M")
|
| 332 |
+
self._assert_insert_conversion(obj, insert, exp, coerced_dtype)
|
| 333 |
+
|
| 334 |
+
# string that can be parsed to appropriate PeriodDtype
|
| 335 |
+
self._assert_insert_conversion(obj, str(insert), exp, coerced_dtype)
|
| 336 |
+
|
| 337 |
+
else:
|
| 338 |
+
result = obj.insert(0, insert)
|
| 339 |
+
expected = obj.astype(object).insert(0, insert)
|
| 340 |
+
tm.assert_index_equal(result, expected)
|
| 341 |
+
|
| 342 |
+
# TODO: ATM inserting '2012-01-01 00:00:00' when we have obj.freq=="M"
|
| 343 |
+
# casts that string to Period[M], not clear that is desirable
|
| 344 |
+
if not isinstance(insert, pd.Timestamp):
|
| 345 |
+
# non-castable string
|
| 346 |
+
result = obj.insert(0, str(insert))
|
| 347 |
+
expected = obj.astype(object).insert(0, str(insert))
|
| 348 |
+
tm.assert_index_equal(result, expected)
|
| 349 |
+
|
| 350 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
| 351 |
+
def test_insert_index_complex128(self):
|
| 352 |
+
raise NotImplementedError
|
| 353 |
+
|
| 354 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
| 355 |
+
def test_insert_index_bool(self):
|
| 356 |
+
raise NotImplementedError
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
class TestWhereCoercion(CoercionBase):
|
| 360 |
+
method = "where"
|
| 361 |
+
_cond = np.array([True, False, True, False])
|
| 362 |
+
|
| 363 |
+
def _assert_where_conversion(
|
| 364 |
+
self, original, cond, values, expected, expected_dtype
|
| 365 |
+
):
|
| 366 |
+
"""test coercion triggered by where"""
|
| 367 |
+
target = original.copy()
|
| 368 |
+
res = target.where(cond, values)
|
| 369 |
+
tm.assert_equal(res, expected)
|
| 370 |
+
assert res.dtype == expected_dtype
|
| 371 |
+
|
| 372 |
+
def _construct_exp(self, obj, klass, fill_val, exp_dtype):
|
| 373 |
+
if fill_val is True:
|
| 374 |
+
values = klass([True, False, True, True])
|
| 375 |
+
elif isinstance(fill_val, (datetime, np.datetime64)):
|
| 376 |
+
values = pd.date_range(fill_val, periods=4)
|
| 377 |
+
else:
|
| 378 |
+
values = klass(x * fill_val for x in [5, 6, 7, 8])
|
| 379 |
+
|
| 380 |
+
exp = klass([obj[0], values[1], obj[2], values[3]], dtype=exp_dtype)
|
| 381 |
+
return values, exp
|
| 382 |
+
|
| 383 |
+
def _run_test(self, obj, fill_val, klass, exp_dtype):
|
| 384 |
+
cond = klass(self._cond)
|
| 385 |
+
|
| 386 |
+
exp = klass([obj[0], fill_val, obj[2], fill_val], dtype=exp_dtype)
|
| 387 |
+
self._assert_where_conversion(obj, cond, fill_val, exp, exp_dtype)
|
| 388 |
+
|
| 389 |
+
values, exp = self._construct_exp(obj, klass, fill_val, exp_dtype)
|
| 390 |
+
self._assert_where_conversion(obj, cond, values, exp, exp_dtype)
|
| 391 |
+
|
| 392 |
+
@pytest.mark.parametrize(
|
| 393 |
+
"fill_val,exp_dtype",
|
| 394 |
+
[(1, object), (1.1, object), (1 + 1j, object), (True, object)],
|
| 395 |
+
)
|
| 396 |
+
def test_where_object(self, index_or_series, fill_val, exp_dtype):
|
| 397 |
+
klass = index_or_series
|
| 398 |
+
obj = klass(list("abcd"))
|
| 399 |
+
assert obj.dtype == object
|
| 400 |
+
self._run_test(obj, fill_val, klass, exp_dtype)
|
| 401 |
+
|
| 402 |
+
@pytest.mark.parametrize(
|
| 403 |
+
"fill_val,exp_dtype",
|
| 404 |
+
[(1, np.int64), (1.1, np.float64), (1 + 1j, np.complex128), (True, object)],
|
| 405 |
+
)
|
| 406 |
+
def test_where_int64(self, index_or_series, fill_val, exp_dtype, request):
|
| 407 |
+
klass = index_or_series
|
| 408 |
+
|
| 409 |
+
obj = klass([1, 2, 3, 4])
|
| 410 |
+
assert obj.dtype == np.int64
|
| 411 |
+
self._run_test(obj, fill_val, klass, exp_dtype)
|
| 412 |
+
|
| 413 |
+
@pytest.mark.parametrize(
|
| 414 |
+
"fill_val, exp_dtype",
|
| 415 |
+
[(1, np.float64), (1.1, np.float64), (1 + 1j, np.complex128), (True, object)],
|
| 416 |
+
)
|
| 417 |
+
def test_where_float64(self, index_or_series, fill_val, exp_dtype, request):
|
| 418 |
+
klass = index_or_series
|
| 419 |
+
|
| 420 |
+
obj = klass([1.1, 2.2, 3.3, 4.4])
|
| 421 |
+
assert obj.dtype == np.float64
|
| 422 |
+
self._run_test(obj, fill_val, klass, exp_dtype)
|
| 423 |
+
|
| 424 |
+
@pytest.mark.parametrize(
|
| 425 |
+
"fill_val,exp_dtype",
|
| 426 |
+
[
|
| 427 |
+
(1, np.complex128),
|
| 428 |
+
(1.1, np.complex128),
|
| 429 |
+
(1 + 1j, np.complex128),
|
| 430 |
+
(True, object),
|
| 431 |
+
],
|
| 432 |
+
)
|
| 433 |
+
def test_where_complex128(self, index_or_series, fill_val, exp_dtype):
|
| 434 |
+
klass = index_or_series
|
| 435 |
+
obj = klass([1 + 1j, 2 + 2j, 3 + 3j, 4 + 4j], dtype=np.complex128)
|
| 436 |
+
assert obj.dtype == np.complex128
|
| 437 |
+
self._run_test(obj, fill_val, klass, exp_dtype)
|
| 438 |
+
|
| 439 |
+
@pytest.mark.parametrize(
|
| 440 |
+
"fill_val,exp_dtype",
|
| 441 |
+
[(1, object), (1.1, object), (1 + 1j, object), (True, np.bool_)],
|
| 442 |
+
)
|
| 443 |
+
def test_where_series_bool(self, fill_val, exp_dtype):
|
| 444 |
+
klass = pd.Series # TODO: use index_or_series once we have Index[bool]
|
| 445 |
+
|
| 446 |
+
obj = klass([True, False, True, False])
|
| 447 |
+
assert obj.dtype == np.bool_
|
| 448 |
+
self._run_test(obj, fill_val, klass, exp_dtype)
|
| 449 |
+
|
| 450 |
+
@pytest.mark.parametrize(
|
| 451 |
+
"fill_val,exp_dtype",
|
| 452 |
+
[
|
| 453 |
+
(pd.Timestamp("2012-01-01"), "datetime64[ns]"),
|
| 454 |
+
(pd.Timestamp("2012-01-01", tz="US/Eastern"), object),
|
| 455 |
+
],
|
| 456 |
+
ids=["datetime64", "datetime64tz"],
|
| 457 |
+
)
|
| 458 |
+
def test_where_datetime64(self, index_or_series, fill_val, exp_dtype):
|
| 459 |
+
klass = index_or_series
|
| 460 |
+
|
| 461 |
+
obj = klass(pd.date_range("2011-01-01", periods=4, freq="D")._with_freq(None))
|
| 462 |
+
assert obj.dtype == "datetime64[ns]"
|
| 463 |
+
|
| 464 |
+
fv = fill_val
|
| 465 |
+
# do the check with each of the available datetime scalars
|
| 466 |
+
if exp_dtype == "datetime64[ns]":
|
| 467 |
+
for scalar in [fv, fv.to_pydatetime(), fv.to_datetime64()]:
|
| 468 |
+
self._run_test(obj, scalar, klass, exp_dtype)
|
| 469 |
+
else:
|
| 470 |
+
for scalar in [fv, fv.to_pydatetime()]:
|
| 471 |
+
self._run_test(obj, fill_val, klass, exp_dtype)
|
| 472 |
+
|
| 473 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
| 474 |
+
def test_where_index_complex128(self):
|
| 475 |
+
raise NotImplementedError
|
| 476 |
+
|
| 477 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
| 478 |
+
def test_where_index_bool(self):
|
| 479 |
+
raise NotImplementedError
|
| 480 |
+
|
| 481 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
| 482 |
+
def test_where_series_timedelta64(self):
|
| 483 |
+
raise NotImplementedError
|
| 484 |
+
|
| 485 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
| 486 |
+
def test_where_series_period(self):
|
| 487 |
+
raise NotImplementedError
|
| 488 |
+
|
| 489 |
+
@pytest.mark.parametrize(
|
| 490 |
+
"value", [pd.Timedelta(days=9), timedelta(days=9), np.timedelta64(9, "D")]
|
| 491 |
+
)
|
| 492 |
+
def test_where_index_timedelta64(self, value):
|
| 493 |
+
tdi = pd.timedelta_range("1 Day", periods=4)
|
| 494 |
+
cond = np.array([True, False, False, True])
|
| 495 |
+
|
| 496 |
+
expected = pd.TimedeltaIndex(["1 Day", value, value, "4 Days"])
|
| 497 |
+
result = tdi.where(cond, value)
|
| 498 |
+
tm.assert_index_equal(result, expected)
|
| 499 |
+
|
| 500 |
+
# wrong-dtyped NaT
|
| 501 |
+
dtnat = np.datetime64("NaT", "ns")
|
| 502 |
+
expected = pd.Index([tdi[0], dtnat, dtnat, tdi[3]], dtype=object)
|
| 503 |
+
assert expected[1] is dtnat
|
| 504 |
+
|
| 505 |
+
result = tdi.where(cond, dtnat)
|
| 506 |
+
tm.assert_index_equal(result, expected)
|
| 507 |
+
|
| 508 |
+
def test_where_index_period(self):
|
| 509 |
+
dti = pd.date_range("2016-01-01", periods=3, freq="QS")
|
| 510 |
+
pi = dti.to_period("Q")
|
| 511 |
+
|
| 512 |
+
cond = np.array([False, True, False])
|
| 513 |
+
|
| 514 |
+
# Passing a valid scalar
|
| 515 |
+
value = pi[-1] + pi.freq * 10
|
| 516 |
+
expected = pd.PeriodIndex([value, pi[1], value])
|
| 517 |
+
result = pi.where(cond, value)
|
| 518 |
+
tm.assert_index_equal(result, expected)
|
| 519 |
+
|
| 520 |
+
# Case passing ndarray[object] of Periods
|
| 521 |
+
other = np.asarray(pi + pi.freq * 10, dtype=object)
|
| 522 |
+
result = pi.where(cond, other)
|
| 523 |
+
expected = pd.PeriodIndex([other[0], pi[1], other[2]])
|
| 524 |
+
tm.assert_index_equal(result, expected)
|
| 525 |
+
|
| 526 |
+
# Passing a mismatched scalar -> casts to object
|
| 527 |
+
td = pd.Timedelta(days=4)
|
| 528 |
+
expected = pd.Index([td, pi[1], td], dtype=object)
|
| 529 |
+
result = pi.where(cond, td)
|
| 530 |
+
tm.assert_index_equal(result, expected)
|
| 531 |
+
|
| 532 |
+
per = pd.Period("2020-04-21", "D")
|
| 533 |
+
expected = pd.Index([per, pi[1], per], dtype=object)
|
| 534 |
+
result = pi.where(cond, per)
|
| 535 |
+
tm.assert_index_equal(result, expected)
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
class TestFillnaSeriesCoercion(CoercionBase):
|
| 539 |
+
# not indexing, but place here for consistency
|
| 540 |
+
|
| 541 |
+
method = "fillna"
|
| 542 |
+
|
| 543 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
| 544 |
+
def test_has_comprehensive_tests(self):
|
| 545 |
+
raise NotImplementedError
|
| 546 |
+
|
| 547 |
+
def _assert_fillna_conversion(self, original, value, expected, expected_dtype):
|
| 548 |
+
"""test coercion triggered by fillna"""
|
| 549 |
+
target = original.copy()
|
| 550 |
+
res = target.fillna(value)
|
| 551 |
+
tm.assert_equal(res, expected)
|
| 552 |
+
assert res.dtype == expected_dtype
|
| 553 |
+
|
| 554 |
+
@pytest.mark.parametrize(
|
| 555 |
+
"fill_val, fill_dtype",
|
| 556 |
+
[(1, object), (1.1, object), (1 + 1j, object), (True, object)],
|
| 557 |
+
)
|
| 558 |
+
def test_fillna_object(self, index_or_series, fill_val, fill_dtype):
|
| 559 |
+
klass = index_or_series
|
| 560 |
+
obj = klass(["a", np.nan, "c", "d"])
|
| 561 |
+
assert obj.dtype == object
|
| 562 |
+
|
| 563 |
+
exp = klass(["a", fill_val, "c", "d"])
|
| 564 |
+
self._assert_fillna_conversion(obj, fill_val, exp, fill_dtype)
|
| 565 |
+
|
| 566 |
+
@pytest.mark.parametrize(
|
| 567 |
+
"fill_val,fill_dtype",
|
| 568 |
+
[(1, np.float64), (1.1, np.float64), (1 + 1j, np.complex128), (True, object)],
|
| 569 |
+
)
|
| 570 |
+
def test_fillna_float64(self, index_or_series, fill_val, fill_dtype):
|
| 571 |
+
klass = index_or_series
|
| 572 |
+
obj = klass([1.1, np.nan, 3.3, 4.4])
|
| 573 |
+
assert obj.dtype == np.float64
|
| 574 |
+
|
| 575 |
+
exp = klass([1.1, fill_val, 3.3, 4.4])
|
| 576 |
+
self._assert_fillna_conversion(obj, fill_val, exp, fill_dtype)
|
| 577 |
+
|
| 578 |
+
@pytest.mark.parametrize(
|
| 579 |
+
"fill_val,fill_dtype",
|
| 580 |
+
[
|
| 581 |
+
(1, np.complex128),
|
| 582 |
+
(1.1, np.complex128),
|
| 583 |
+
(1 + 1j, np.complex128),
|
| 584 |
+
(True, object),
|
| 585 |
+
],
|
| 586 |
+
)
|
| 587 |
+
def test_fillna_complex128(self, index_or_series, fill_val, fill_dtype):
|
| 588 |
+
klass = index_or_series
|
| 589 |
+
obj = klass([1 + 1j, np.nan, 3 + 3j, 4 + 4j], dtype=np.complex128)
|
| 590 |
+
assert obj.dtype == np.complex128
|
| 591 |
+
|
| 592 |
+
exp = klass([1 + 1j, fill_val, 3 + 3j, 4 + 4j])
|
| 593 |
+
self._assert_fillna_conversion(obj, fill_val, exp, fill_dtype)
|
| 594 |
+
|
| 595 |
+
@pytest.mark.parametrize(
|
| 596 |
+
"fill_val,fill_dtype",
|
| 597 |
+
[
|
| 598 |
+
(pd.Timestamp("2012-01-01"), "datetime64[ns]"),
|
| 599 |
+
(pd.Timestamp("2012-01-01", tz="US/Eastern"), object),
|
| 600 |
+
(1, object),
|
| 601 |
+
("x", object),
|
| 602 |
+
],
|
| 603 |
+
ids=["datetime64", "datetime64tz", "object", "object"],
|
| 604 |
+
)
|
| 605 |
+
def test_fillna_datetime(self, index_or_series, fill_val, fill_dtype):
|
| 606 |
+
klass = index_or_series
|
| 607 |
+
obj = klass(
|
| 608 |
+
[
|
| 609 |
+
pd.Timestamp("2011-01-01"),
|
| 610 |
+
pd.NaT,
|
| 611 |
+
pd.Timestamp("2011-01-03"),
|
| 612 |
+
pd.Timestamp("2011-01-04"),
|
| 613 |
+
]
|
| 614 |
+
)
|
| 615 |
+
assert obj.dtype == "datetime64[ns]"
|
| 616 |
+
|
| 617 |
+
exp = klass(
|
| 618 |
+
[
|
| 619 |
+
pd.Timestamp("2011-01-01"),
|
| 620 |
+
fill_val,
|
| 621 |
+
pd.Timestamp("2011-01-03"),
|
| 622 |
+
pd.Timestamp("2011-01-04"),
|
| 623 |
+
]
|
| 624 |
+
)
|
| 625 |
+
self._assert_fillna_conversion(obj, fill_val, exp, fill_dtype)
|
| 626 |
+
|
| 627 |
+
@pytest.mark.parametrize(
|
| 628 |
+
"fill_val,fill_dtype",
|
| 629 |
+
[
|
| 630 |
+
(pd.Timestamp("2012-01-01", tz="US/Eastern"), "datetime64[ns, US/Eastern]"),
|
| 631 |
+
(pd.Timestamp("2012-01-01"), object),
|
| 632 |
+
# pre-2.0 with a mismatched tz we would get object result
|
| 633 |
+
(pd.Timestamp("2012-01-01", tz="Asia/Tokyo"), "datetime64[ns, US/Eastern]"),
|
| 634 |
+
(1, object),
|
| 635 |
+
("x", object),
|
| 636 |
+
],
|
| 637 |
+
)
|
| 638 |
+
def test_fillna_datetime64tz(self, index_or_series, fill_val, fill_dtype):
|
| 639 |
+
klass = index_or_series
|
| 640 |
+
tz = "US/Eastern"
|
| 641 |
+
|
| 642 |
+
obj = klass(
|
| 643 |
+
[
|
| 644 |
+
pd.Timestamp("2011-01-01", tz=tz),
|
| 645 |
+
pd.NaT,
|
| 646 |
+
pd.Timestamp("2011-01-03", tz=tz),
|
| 647 |
+
pd.Timestamp("2011-01-04", tz=tz),
|
| 648 |
+
]
|
| 649 |
+
)
|
| 650 |
+
assert obj.dtype == "datetime64[ns, US/Eastern]"
|
| 651 |
+
|
| 652 |
+
if getattr(fill_val, "tz", None) is None:
|
| 653 |
+
fv = fill_val
|
| 654 |
+
else:
|
| 655 |
+
fv = fill_val.tz_convert(tz)
|
| 656 |
+
exp = klass(
|
| 657 |
+
[
|
| 658 |
+
pd.Timestamp("2011-01-01", tz=tz),
|
| 659 |
+
fv,
|
| 660 |
+
pd.Timestamp("2011-01-03", tz=tz),
|
| 661 |
+
pd.Timestamp("2011-01-04", tz=tz),
|
| 662 |
+
]
|
| 663 |
+
)
|
| 664 |
+
self._assert_fillna_conversion(obj, fill_val, exp, fill_dtype)
|
| 665 |
+
|
| 666 |
+
@pytest.mark.parametrize(
|
| 667 |
+
"fill_val",
|
| 668 |
+
[
|
| 669 |
+
1,
|
| 670 |
+
1.1,
|
| 671 |
+
1 + 1j,
|
| 672 |
+
True,
|
| 673 |
+
pd.Interval(1, 2, closed="left"),
|
| 674 |
+
pd.Timestamp("2012-01-01", tz="US/Eastern"),
|
| 675 |
+
pd.Timestamp("2012-01-01"),
|
| 676 |
+
pd.Timedelta(days=1),
|
| 677 |
+
pd.Period("2016-01-01", "D"),
|
| 678 |
+
],
|
| 679 |
+
)
|
| 680 |
+
def test_fillna_interval(self, index_or_series, fill_val):
|
| 681 |
+
ii = pd.interval_range(1.0, 5.0, closed="right").insert(1, np.nan)
|
| 682 |
+
assert isinstance(ii.dtype, pd.IntervalDtype)
|
| 683 |
+
obj = index_or_series(ii)
|
| 684 |
+
|
| 685 |
+
exp = index_or_series([ii[0], fill_val, ii[2], ii[3], ii[4]], dtype=object)
|
| 686 |
+
|
| 687 |
+
fill_dtype = object
|
| 688 |
+
self._assert_fillna_conversion(obj, fill_val, exp, fill_dtype)
|
| 689 |
+
|
| 690 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
| 691 |
+
def test_fillna_series_int64(self):
|
| 692 |
+
raise NotImplementedError
|
| 693 |
+
|
| 694 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
| 695 |
+
def test_fillna_index_int64(self):
|
| 696 |
+
raise NotImplementedError
|
| 697 |
+
|
| 698 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
| 699 |
+
def test_fillna_series_bool(self):
|
| 700 |
+
raise NotImplementedError
|
| 701 |
+
|
| 702 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
| 703 |
+
def test_fillna_index_bool(self):
|
| 704 |
+
raise NotImplementedError
|
| 705 |
+
|
| 706 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
| 707 |
+
def test_fillna_series_timedelta64(self):
|
| 708 |
+
raise NotImplementedError
|
| 709 |
+
|
| 710 |
+
@pytest.mark.parametrize(
|
| 711 |
+
"fill_val",
|
| 712 |
+
[
|
| 713 |
+
1,
|
| 714 |
+
1.1,
|
| 715 |
+
1 + 1j,
|
| 716 |
+
True,
|
| 717 |
+
pd.Interval(1, 2, closed="left"),
|
| 718 |
+
pd.Timestamp("2012-01-01", tz="US/Eastern"),
|
| 719 |
+
pd.Timestamp("2012-01-01"),
|
| 720 |
+
pd.Timedelta(days=1),
|
| 721 |
+
pd.Period("2016-01-01", "W"),
|
| 722 |
+
],
|
| 723 |
+
)
|
| 724 |
+
def test_fillna_series_period(self, index_or_series, fill_val):
|
| 725 |
+
pi = pd.period_range("2016-01-01", periods=4, freq="D").insert(1, pd.NaT)
|
| 726 |
+
assert isinstance(pi.dtype, pd.PeriodDtype)
|
| 727 |
+
obj = index_or_series(pi)
|
| 728 |
+
|
| 729 |
+
exp = index_or_series([pi[0], fill_val, pi[2], pi[3], pi[4]], dtype=object)
|
| 730 |
+
|
| 731 |
+
fill_dtype = object
|
| 732 |
+
self._assert_fillna_conversion(obj, fill_val, exp, fill_dtype)
|
| 733 |
+
|
| 734 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
| 735 |
+
def test_fillna_index_timedelta64(self):
|
| 736 |
+
raise NotImplementedError
|
| 737 |
+
|
| 738 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
| 739 |
+
def test_fillna_index_period(self):
|
| 740 |
+
raise NotImplementedError
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
class TestReplaceSeriesCoercion(CoercionBase):
|
| 744 |
+
klasses = ["series"]
|
| 745 |
+
method = "replace"
|
| 746 |
+
|
| 747 |
+
rep: dict[str, list] = {}
|
| 748 |
+
rep["object"] = ["a", "b"]
|
| 749 |
+
rep["int64"] = [4, 5]
|
| 750 |
+
rep["float64"] = [1.1, 2.2]
|
| 751 |
+
rep["complex128"] = [1 + 1j, 2 + 2j]
|
| 752 |
+
rep["bool"] = [True, False]
|
| 753 |
+
rep["datetime64[ns]"] = [pd.Timestamp("2011-01-01"), pd.Timestamp("2011-01-03")]
|
| 754 |
+
|
| 755 |
+
for tz in ["UTC", "US/Eastern"]:
|
| 756 |
+
# to test tz => different tz replacement
|
| 757 |
+
key = f"datetime64[ns, {tz}]"
|
| 758 |
+
rep[key] = [
|
| 759 |
+
pd.Timestamp("2011-01-01", tz=tz),
|
| 760 |
+
pd.Timestamp("2011-01-03", tz=tz),
|
| 761 |
+
]
|
| 762 |
+
|
| 763 |
+
rep["timedelta64[ns]"] = [pd.Timedelta("1 day"), pd.Timedelta("2 day")]
|
| 764 |
+
|
| 765 |
+
@pytest.fixture(params=["dict", "series"])
|
| 766 |
+
def how(self, request):
|
| 767 |
+
return request.param
|
| 768 |
+
|
| 769 |
+
@pytest.fixture(
|
| 770 |
+
params=[
|
| 771 |
+
"object",
|
| 772 |
+
"int64",
|
| 773 |
+
"float64",
|
| 774 |
+
"complex128",
|
| 775 |
+
"bool",
|
| 776 |
+
"datetime64[ns]",
|
| 777 |
+
"datetime64[ns, UTC]",
|
| 778 |
+
"datetime64[ns, US/Eastern]",
|
| 779 |
+
"timedelta64[ns]",
|
| 780 |
+
]
|
| 781 |
+
)
|
| 782 |
+
def from_key(self, request):
|
| 783 |
+
return request.param
|
| 784 |
+
|
| 785 |
+
@pytest.fixture(
|
| 786 |
+
params=[
|
| 787 |
+
"object",
|
| 788 |
+
"int64",
|
| 789 |
+
"float64",
|
| 790 |
+
"complex128",
|
| 791 |
+
"bool",
|
| 792 |
+
"datetime64[ns]",
|
| 793 |
+
"datetime64[ns, UTC]",
|
| 794 |
+
"datetime64[ns, US/Eastern]",
|
| 795 |
+
"timedelta64[ns]",
|
| 796 |
+
],
|
| 797 |
+
ids=[
|
| 798 |
+
"object",
|
| 799 |
+
"int64",
|
| 800 |
+
"float64",
|
| 801 |
+
"complex128",
|
| 802 |
+
"bool",
|
| 803 |
+
"datetime64",
|
| 804 |
+
"datetime64tz",
|
| 805 |
+
"datetime64tz",
|
| 806 |
+
"timedelta64",
|
| 807 |
+
],
|
| 808 |
+
)
|
| 809 |
+
def to_key(self, request):
|
| 810 |
+
return request.param
|
| 811 |
+
|
| 812 |
+
@pytest.fixture
|
| 813 |
+
def replacer(self, how, from_key, to_key):
|
| 814 |
+
"""
|
| 815 |
+
Object we will pass to `Series.replace`
|
| 816 |
+
"""
|
| 817 |
+
if how == "dict":
|
| 818 |
+
replacer = dict(zip(self.rep[from_key], self.rep[to_key]))
|
| 819 |
+
elif how == "series":
|
| 820 |
+
replacer = pd.Series(self.rep[to_key], index=self.rep[from_key])
|
| 821 |
+
else:
|
| 822 |
+
raise ValueError
|
| 823 |
+
return replacer
|
| 824 |
+
|
| 825 |
+
def test_replace_series(self, how, to_key, from_key, replacer):
|
| 826 |
+
index = pd.Index([3, 4], name="xxx")
|
| 827 |
+
obj = pd.Series(self.rep[from_key], index=index, name="yyy")
|
| 828 |
+
assert obj.dtype == from_key
|
| 829 |
+
|
| 830 |
+
if from_key.startswith("datetime") and to_key.startswith("datetime"):
|
| 831 |
+
# tested below
|
| 832 |
+
return
|
| 833 |
+
elif from_key in ["datetime64[ns, US/Eastern]", "datetime64[ns, UTC]"]:
|
| 834 |
+
# tested below
|
| 835 |
+
return
|
| 836 |
+
|
| 837 |
+
result = obj.replace(replacer)
|
| 838 |
+
|
| 839 |
+
if (from_key == "float64" and to_key in ("int64")) or (
|
| 840 |
+
from_key == "complex128" and to_key in ("int64", "float64")
|
| 841 |
+
):
|
| 842 |
+
if not IS64 or is_platform_windows():
|
| 843 |
+
pytest.skip(f"32-bit platform buggy: {from_key} -> {to_key}")
|
| 844 |
+
|
| 845 |
+
# Expected: do not downcast by replacement
|
| 846 |
+
exp = pd.Series(self.rep[to_key], index=index, name="yyy", dtype=from_key)
|
| 847 |
+
|
| 848 |
+
else:
|
| 849 |
+
exp = pd.Series(self.rep[to_key], index=index, name="yyy")
|
| 850 |
+
assert exp.dtype == to_key
|
| 851 |
+
|
| 852 |
+
tm.assert_series_equal(result, exp)
|
| 853 |
+
|
| 854 |
+
@pytest.mark.parametrize(
|
| 855 |
+
"to_key",
|
| 856 |
+
["timedelta64[ns]", "bool", "object", "complex128", "float64", "int64"],
|
| 857 |
+
indirect=True,
|
| 858 |
+
)
|
| 859 |
+
@pytest.mark.parametrize(
|
| 860 |
+
"from_key", ["datetime64[ns, UTC]", "datetime64[ns, US/Eastern]"], indirect=True
|
| 861 |
+
)
|
| 862 |
+
def test_replace_series_datetime_tz(self, how, to_key, from_key, replacer):
|
| 863 |
+
index = pd.Index([3, 4], name="xyz")
|
| 864 |
+
obj = pd.Series(self.rep[from_key], index=index, name="yyy")
|
| 865 |
+
assert obj.dtype == from_key
|
| 866 |
+
|
| 867 |
+
result = obj.replace(replacer)
|
| 868 |
+
|
| 869 |
+
exp = pd.Series(self.rep[to_key], index=index, name="yyy")
|
| 870 |
+
assert exp.dtype == to_key
|
| 871 |
+
|
| 872 |
+
tm.assert_series_equal(result, exp)
|
| 873 |
+
|
| 874 |
+
@pytest.mark.parametrize(
|
| 875 |
+
"to_key",
|
| 876 |
+
["datetime64[ns]", "datetime64[ns, UTC]", "datetime64[ns, US/Eastern]"],
|
| 877 |
+
indirect=True,
|
| 878 |
+
)
|
| 879 |
+
@pytest.mark.parametrize(
|
| 880 |
+
"from_key",
|
| 881 |
+
["datetime64[ns]", "datetime64[ns, UTC]", "datetime64[ns, US/Eastern]"],
|
| 882 |
+
indirect=True,
|
| 883 |
+
)
|
| 884 |
+
def test_replace_series_datetime_datetime(self, how, to_key, from_key, replacer):
|
| 885 |
+
index = pd.Index([3, 4], name="xyz")
|
| 886 |
+
obj = pd.Series(self.rep[from_key], index=index, name="yyy")
|
| 887 |
+
assert obj.dtype == from_key
|
| 888 |
+
|
| 889 |
+
result = obj.replace(replacer)
|
| 890 |
+
|
| 891 |
+
exp = pd.Series(self.rep[to_key], index=index, name="yyy")
|
| 892 |
+
if isinstance(obj.dtype, pd.DatetimeTZDtype) and isinstance(
|
| 893 |
+
exp.dtype, pd.DatetimeTZDtype
|
| 894 |
+
):
|
| 895 |
+
# with mismatched tzs, we retain the original dtype as of 2.0
|
| 896 |
+
exp = exp.astype(obj.dtype)
|
| 897 |
+
else:
|
| 898 |
+
assert exp.dtype == to_key
|
| 899 |
+
|
| 900 |
+
tm.assert_series_equal(result, exp)
|
| 901 |
+
|
| 902 |
+
@pytest.mark.xfail(reason="Test not implemented")
|
| 903 |
+
def test_replace_series_period(self):
|
| 904 |
+
raise NotImplementedError
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/test_floats.py
ADDED
|
@@ -0,0 +1,675 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from pandas import (
|
| 5 |
+
DataFrame,
|
| 6 |
+
Index,
|
| 7 |
+
RangeIndex,
|
| 8 |
+
Series,
|
| 9 |
+
)
|
| 10 |
+
import pandas._testing as tm
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def gen_obj(klass, index):
|
| 14 |
+
if klass is Series:
|
| 15 |
+
obj = Series(np.arange(len(index)), index=index)
|
| 16 |
+
else:
|
| 17 |
+
obj = DataFrame(
|
| 18 |
+
np.random.randn(len(index), len(index)), index=index, columns=index
|
| 19 |
+
)
|
| 20 |
+
return obj
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class TestFloatIndexers:
|
| 24 |
+
def check(self, result, original, indexer, getitem):
|
| 25 |
+
"""
|
| 26 |
+
comparator for results
|
| 27 |
+
we need to take care if we are indexing on a
|
| 28 |
+
Series or a frame
|
| 29 |
+
"""
|
| 30 |
+
if isinstance(original, Series):
|
| 31 |
+
expected = original.iloc[indexer]
|
| 32 |
+
else:
|
| 33 |
+
if getitem:
|
| 34 |
+
expected = original.iloc[:, indexer]
|
| 35 |
+
else:
|
| 36 |
+
expected = original.iloc[indexer]
|
| 37 |
+
|
| 38 |
+
tm.assert_almost_equal(result, expected)
|
| 39 |
+
|
| 40 |
+
@pytest.mark.parametrize(
|
| 41 |
+
"index_func",
|
| 42 |
+
[
|
| 43 |
+
tm.makeStringIndex,
|
| 44 |
+
tm.makeCategoricalIndex,
|
| 45 |
+
tm.makeDateIndex,
|
| 46 |
+
tm.makeTimedeltaIndex,
|
| 47 |
+
tm.makePeriodIndex,
|
| 48 |
+
],
|
| 49 |
+
)
|
| 50 |
+
def test_scalar_non_numeric(self, index_func, frame_or_series, indexer_sl):
|
| 51 |
+
# GH 4892
|
| 52 |
+
# float_indexers should raise exceptions
|
| 53 |
+
# on appropriate Index types & accessors
|
| 54 |
+
|
| 55 |
+
i = index_func(5)
|
| 56 |
+
s = gen_obj(frame_or_series, i)
|
| 57 |
+
|
| 58 |
+
# getting
|
| 59 |
+
with pytest.raises(KeyError, match="^3.0$"):
|
| 60 |
+
indexer_sl(s)[3.0]
|
| 61 |
+
|
| 62 |
+
# contains
|
| 63 |
+
assert 3.0 not in s
|
| 64 |
+
|
| 65 |
+
s2 = s.copy()
|
| 66 |
+
indexer_sl(s2)[3.0] = 10
|
| 67 |
+
|
| 68 |
+
if indexer_sl is tm.setitem:
|
| 69 |
+
assert 3.0 in s2.axes[-1]
|
| 70 |
+
elif indexer_sl is tm.loc:
|
| 71 |
+
assert 3.0 in s2.axes[0]
|
| 72 |
+
else:
|
| 73 |
+
assert 3.0 not in s2.axes[0]
|
| 74 |
+
assert 3.0 not in s2.axes[-1]
|
| 75 |
+
|
| 76 |
+
@pytest.mark.parametrize(
|
| 77 |
+
"index_func",
|
| 78 |
+
[
|
| 79 |
+
tm.makeStringIndex,
|
| 80 |
+
tm.makeCategoricalIndex,
|
| 81 |
+
tm.makeDateIndex,
|
| 82 |
+
tm.makeTimedeltaIndex,
|
| 83 |
+
tm.makePeriodIndex,
|
| 84 |
+
],
|
| 85 |
+
)
|
| 86 |
+
def test_scalar_non_numeric_series_fallback(self, index_func):
|
| 87 |
+
# fallsback to position selection, series only
|
| 88 |
+
i = index_func(5)
|
| 89 |
+
s = Series(np.arange(len(i)), index=i)
|
| 90 |
+
s[3]
|
| 91 |
+
with pytest.raises(KeyError, match="^3.0$"):
|
| 92 |
+
s[3.0]
|
| 93 |
+
|
| 94 |
+
def test_scalar_with_mixed(self, indexer_sl):
|
| 95 |
+
s2 = Series([1, 2, 3], index=["a", "b", "c"])
|
| 96 |
+
s3 = Series([1, 2, 3], index=["a", "b", 1.5])
|
| 97 |
+
|
| 98 |
+
# lookup in a pure string index with an invalid indexer
|
| 99 |
+
|
| 100 |
+
with pytest.raises(KeyError, match="^1.0$"):
|
| 101 |
+
indexer_sl(s2)[1.0]
|
| 102 |
+
|
| 103 |
+
with pytest.raises(KeyError, match=r"^1\.0$"):
|
| 104 |
+
indexer_sl(s2)[1.0]
|
| 105 |
+
|
| 106 |
+
result = indexer_sl(s2)["b"]
|
| 107 |
+
expected = 2
|
| 108 |
+
assert result == expected
|
| 109 |
+
|
| 110 |
+
# mixed index so we have label
|
| 111 |
+
# indexing
|
| 112 |
+
with pytest.raises(KeyError, match="^1.0$"):
|
| 113 |
+
indexer_sl(s3)[1.0]
|
| 114 |
+
|
| 115 |
+
if indexer_sl is not tm.loc:
|
| 116 |
+
# __getitem__ falls back to positional
|
| 117 |
+
result = s3[1]
|
| 118 |
+
expected = 2
|
| 119 |
+
assert result == expected
|
| 120 |
+
|
| 121 |
+
with pytest.raises(KeyError, match=r"^1\.0$"):
|
| 122 |
+
indexer_sl(s3)[1.0]
|
| 123 |
+
|
| 124 |
+
result = indexer_sl(s3)[1.5]
|
| 125 |
+
expected = 3
|
| 126 |
+
assert result == expected
|
| 127 |
+
|
| 128 |
+
@pytest.mark.parametrize("index_func", [tm.makeIntIndex, tm.makeRangeIndex])
|
| 129 |
+
def test_scalar_integer(self, index_func, frame_or_series, indexer_sl):
|
| 130 |
+
getitem = indexer_sl is not tm.loc
|
| 131 |
+
|
| 132 |
+
# test how scalar float indexers work on int indexes
|
| 133 |
+
|
| 134 |
+
# integer index
|
| 135 |
+
i = index_func(5)
|
| 136 |
+
obj = gen_obj(frame_or_series, i)
|
| 137 |
+
|
| 138 |
+
# coerce to equal int
|
| 139 |
+
|
| 140 |
+
result = indexer_sl(obj)[3.0]
|
| 141 |
+
self.check(result, obj, 3, getitem)
|
| 142 |
+
|
| 143 |
+
if isinstance(obj, Series):
|
| 144 |
+
|
| 145 |
+
def compare(x, y):
|
| 146 |
+
assert x == y
|
| 147 |
+
|
| 148 |
+
expected = 100
|
| 149 |
+
else:
|
| 150 |
+
compare = tm.assert_series_equal
|
| 151 |
+
if getitem:
|
| 152 |
+
expected = Series(100, index=range(len(obj)), name=3)
|
| 153 |
+
else:
|
| 154 |
+
expected = Series(100.0, index=range(len(obj)), name=3)
|
| 155 |
+
|
| 156 |
+
s2 = obj.copy()
|
| 157 |
+
indexer_sl(s2)[3.0] = 100
|
| 158 |
+
|
| 159 |
+
result = indexer_sl(s2)[3.0]
|
| 160 |
+
compare(result, expected)
|
| 161 |
+
|
| 162 |
+
result = indexer_sl(s2)[3]
|
| 163 |
+
compare(result, expected)
|
| 164 |
+
|
| 165 |
+
@pytest.mark.parametrize("index_func", [tm.makeIntIndex, tm.makeRangeIndex])
|
| 166 |
+
def test_scalar_integer_contains_float(self, index_func, frame_or_series):
|
| 167 |
+
# contains
|
| 168 |
+
# integer index
|
| 169 |
+
index = index_func(5)
|
| 170 |
+
obj = gen_obj(frame_or_series, index)
|
| 171 |
+
|
| 172 |
+
# coerce to equal int
|
| 173 |
+
assert 3.0 in obj
|
| 174 |
+
|
| 175 |
+
def test_scalar_float(self, frame_or_series):
|
| 176 |
+
# scalar float indexers work on a float index
|
| 177 |
+
index = Index(np.arange(5.0))
|
| 178 |
+
s = gen_obj(frame_or_series, index)
|
| 179 |
+
|
| 180 |
+
# assert all operations except for iloc are ok
|
| 181 |
+
indexer = index[3]
|
| 182 |
+
for idxr in [tm.loc, tm.setitem]:
|
| 183 |
+
getitem = idxr is not tm.loc
|
| 184 |
+
|
| 185 |
+
# getting
|
| 186 |
+
result = idxr(s)[indexer]
|
| 187 |
+
self.check(result, s, 3, getitem)
|
| 188 |
+
|
| 189 |
+
# setting
|
| 190 |
+
s2 = s.copy()
|
| 191 |
+
|
| 192 |
+
result = idxr(s2)[indexer]
|
| 193 |
+
self.check(result, s, 3, getitem)
|
| 194 |
+
|
| 195 |
+
# random float is a KeyError
|
| 196 |
+
with pytest.raises(KeyError, match=r"^3\.5$"):
|
| 197 |
+
idxr(s)[3.5]
|
| 198 |
+
|
| 199 |
+
# contains
|
| 200 |
+
assert 3.0 in s
|
| 201 |
+
|
| 202 |
+
# iloc succeeds with an integer
|
| 203 |
+
expected = s.iloc[3]
|
| 204 |
+
s2 = s.copy()
|
| 205 |
+
|
| 206 |
+
s2.iloc[3] = expected
|
| 207 |
+
result = s2.iloc[3]
|
| 208 |
+
self.check(result, s, 3, False)
|
| 209 |
+
|
| 210 |
+
@pytest.mark.parametrize(
|
| 211 |
+
"index_func",
|
| 212 |
+
[
|
| 213 |
+
tm.makeStringIndex,
|
| 214 |
+
tm.makeDateIndex,
|
| 215 |
+
tm.makeTimedeltaIndex,
|
| 216 |
+
tm.makePeriodIndex,
|
| 217 |
+
],
|
| 218 |
+
)
|
| 219 |
+
@pytest.mark.parametrize("idx", [slice(3.0, 4), slice(3, 4.0), slice(3.0, 4.0)])
|
| 220 |
+
def test_slice_non_numeric(self, index_func, idx, frame_or_series, indexer_sli):
|
| 221 |
+
# GH 4892
|
| 222 |
+
# float_indexers should raise exceptions
|
| 223 |
+
# on appropriate Index types & accessors
|
| 224 |
+
|
| 225 |
+
index = index_func(5)
|
| 226 |
+
s = gen_obj(frame_or_series, index)
|
| 227 |
+
|
| 228 |
+
# getitem
|
| 229 |
+
if indexer_sli is tm.iloc:
|
| 230 |
+
msg = (
|
| 231 |
+
"cannot do positional indexing "
|
| 232 |
+
rf"on {type(index).__name__} with these indexers \[(3|4)\.0\] of "
|
| 233 |
+
"type float"
|
| 234 |
+
)
|
| 235 |
+
else:
|
| 236 |
+
msg = (
|
| 237 |
+
"cannot do slice indexing "
|
| 238 |
+
rf"on {type(index).__name__} with these indexers "
|
| 239 |
+
r"\[(3|4)(\.0)?\] "
|
| 240 |
+
r"of type (float|int)"
|
| 241 |
+
)
|
| 242 |
+
with pytest.raises(TypeError, match=msg):
|
| 243 |
+
indexer_sli(s)[idx]
|
| 244 |
+
|
| 245 |
+
# setitem
|
| 246 |
+
if indexer_sli is tm.iloc:
|
| 247 |
+
# otherwise we keep the same message as above
|
| 248 |
+
msg = "slice indices must be integers or None or have an __index__ method"
|
| 249 |
+
with pytest.raises(TypeError, match=msg):
|
| 250 |
+
indexer_sli(s)[idx] = 0
|
| 251 |
+
|
| 252 |
+
def test_slice_integer(self):
|
| 253 |
+
# same as above, but for Integer based indexes
|
| 254 |
+
# these coerce to a like integer
|
| 255 |
+
# oob indicates if we are out of bounds
|
| 256 |
+
# of positional indexing
|
| 257 |
+
for index, oob in [
|
| 258 |
+
(Index(np.arange(5, dtype=np.int64)), False),
|
| 259 |
+
(RangeIndex(5), False),
|
| 260 |
+
(Index(np.arange(5, dtype=np.int64) + 10), True),
|
| 261 |
+
]:
|
| 262 |
+
# s is an in-range index
|
| 263 |
+
s = Series(range(5), index=index)
|
| 264 |
+
|
| 265 |
+
# getitem
|
| 266 |
+
for idx in [slice(3.0, 4), slice(3, 4.0), slice(3.0, 4.0)]:
|
| 267 |
+
result = s.loc[idx]
|
| 268 |
+
|
| 269 |
+
# these are all label indexing
|
| 270 |
+
# except getitem which is positional
|
| 271 |
+
# empty
|
| 272 |
+
if oob:
|
| 273 |
+
indexer = slice(0, 0)
|
| 274 |
+
else:
|
| 275 |
+
indexer = slice(3, 5)
|
| 276 |
+
self.check(result, s, indexer, False)
|
| 277 |
+
|
| 278 |
+
# getitem out-of-bounds
|
| 279 |
+
for idx in [slice(-6, 6), slice(-6.0, 6.0)]:
|
| 280 |
+
result = s.loc[idx]
|
| 281 |
+
|
| 282 |
+
# these are all label indexing
|
| 283 |
+
# except getitem which is positional
|
| 284 |
+
# empty
|
| 285 |
+
if oob:
|
| 286 |
+
indexer = slice(0, 0)
|
| 287 |
+
else:
|
| 288 |
+
indexer = slice(-6, 6)
|
| 289 |
+
self.check(result, s, indexer, False)
|
| 290 |
+
|
| 291 |
+
# positional indexing
|
| 292 |
+
msg = (
|
| 293 |
+
"cannot do slice indexing "
|
| 294 |
+
rf"on {type(index).__name__} with these indexers \[-6\.0\] of "
|
| 295 |
+
"type float"
|
| 296 |
+
)
|
| 297 |
+
with pytest.raises(TypeError, match=msg):
|
| 298 |
+
s[slice(-6.0, 6.0)]
|
| 299 |
+
|
| 300 |
+
# getitem odd floats
|
| 301 |
+
for idx, res1 in [
|
| 302 |
+
(slice(2.5, 4), slice(3, 5)),
|
| 303 |
+
(slice(2, 3.5), slice(2, 4)),
|
| 304 |
+
(slice(2.5, 3.5), slice(3, 4)),
|
| 305 |
+
]:
|
| 306 |
+
result = s.loc[idx]
|
| 307 |
+
if oob:
|
| 308 |
+
res = slice(0, 0)
|
| 309 |
+
else:
|
| 310 |
+
res = res1
|
| 311 |
+
|
| 312 |
+
self.check(result, s, res, False)
|
| 313 |
+
|
| 314 |
+
# positional indexing
|
| 315 |
+
msg = (
|
| 316 |
+
"cannot do slice indexing "
|
| 317 |
+
rf"on {type(index).__name__} with these indexers \[(2|3)\.5\] of "
|
| 318 |
+
"type float"
|
| 319 |
+
)
|
| 320 |
+
with pytest.raises(TypeError, match=msg):
|
| 321 |
+
s[idx]
|
| 322 |
+
|
| 323 |
+
@pytest.mark.parametrize("idx", [slice(2, 4.0), slice(2.0, 4), slice(2.0, 4.0)])
|
| 324 |
+
def test_integer_positional_indexing(self, idx):
|
| 325 |
+
"""make sure that we are raising on positional indexing
|
| 326 |
+
w.r.t. an integer index
|
| 327 |
+
"""
|
| 328 |
+
s = Series(range(2, 6), index=range(2, 6))
|
| 329 |
+
|
| 330 |
+
result = s[2:4]
|
| 331 |
+
expected = s.iloc[2:4]
|
| 332 |
+
tm.assert_series_equal(result, expected)
|
| 333 |
+
|
| 334 |
+
klass = RangeIndex
|
| 335 |
+
msg = (
|
| 336 |
+
"cannot do (slice|positional) indexing "
|
| 337 |
+
rf"on {klass.__name__} with these indexers \[(2|4)\.0\] of "
|
| 338 |
+
"type float"
|
| 339 |
+
)
|
| 340 |
+
with pytest.raises(TypeError, match=msg):
|
| 341 |
+
s[idx]
|
| 342 |
+
with pytest.raises(TypeError, match=msg):
|
| 343 |
+
s.iloc[idx]
|
| 344 |
+
|
| 345 |
+
@pytest.mark.parametrize("index_func", [tm.makeIntIndex, tm.makeRangeIndex])
|
| 346 |
+
def test_slice_integer_frame_getitem(self, index_func):
|
| 347 |
+
# similar to above, but on the getitem dim (of a DataFrame)
|
| 348 |
+
index = index_func(5)
|
| 349 |
+
|
| 350 |
+
s = DataFrame(np.random.randn(5, 2), index=index)
|
| 351 |
+
|
| 352 |
+
# getitem
|
| 353 |
+
for idx in [slice(0.0, 1), slice(0, 1.0), slice(0.0, 1.0)]:
|
| 354 |
+
result = s.loc[idx]
|
| 355 |
+
indexer = slice(0, 2)
|
| 356 |
+
self.check(result, s, indexer, False)
|
| 357 |
+
|
| 358 |
+
# positional indexing
|
| 359 |
+
msg = (
|
| 360 |
+
"cannot do slice indexing "
|
| 361 |
+
rf"on {type(index).__name__} with these indexers \[(0|1)\.0\] of "
|
| 362 |
+
"type float"
|
| 363 |
+
)
|
| 364 |
+
with pytest.raises(TypeError, match=msg):
|
| 365 |
+
s[idx]
|
| 366 |
+
|
| 367 |
+
# getitem out-of-bounds
|
| 368 |
+
for idx in [slice(-10, 10), slice(-10.0, 10.0)]:
|
| 369 |
+
result = s.loc[idx]
|
| 370 |
+
self.check(result, s, slice(-10, 10), True)
|
| 371 |
+
|
| 372 |
+
# positional indexing
|
| 373 |
+
msg = (
|
| 374 |
+
"cannot do slice indexing "
|
| 375 |
+
rf"on {type(index).__name__} with these indexers \[-10\.0\] of "
|
| 376 |
+
"type float"
|
| 377 |
+
)
|
| 378 |
+
with pytest.raises(TypeError, match=msg):
|
| 379 |
+
s[slice(-10.0, 10.0)]
|
| 380 |
+
|
| 381 |
+
# getitem odd floats
|
| 382 |
+
for idx, res in [
|
| 383 |
+
(slice(0.5, 1), slice(1, 2)),
|
| 384 |
+
(slice(0, 0.5), slice(0, 1)),
|
| 385 |
+
(slice(0.5, 1.5), slice(1, 2)),
|
| 386 |
+
]:
|
| 387 |
+
result = s.loc[idx]
|
| 388 |
+
self.check(result, s, res, False)
|
| 389 |
+
|
| 390 |
+
# positional indexing
|
| 391 |
+
msg = (
|
| 392 |
+
"cannot do slice indexing "
|
| 393 |
+
rf"on {type(index).__name__} with these indexers \[0\.5\] of "
|
| 394 |
+
"type float"
|
| 395 |
+
)
|
| 396 |
+
with pytest.raises(TypeError, match=msg):
|
| 397 |
+
s[idx]
|
| 398 |
+
|
| 399 |
+
@pytest.mark.parametrize("idx", [slice(3.0, 4), slice(3, 4.0), slice(3.0, 4.0)])
|
| 400 |
+
@pytest.mark.parametrize("index_func", [tm.makeIntIndex, tm.makeRangeIndex])
|
| 401 |
+
def test_float_slice_getitem_with_integer_index_raises(self, idx, index_func):
|
| 402 |
+
# similar to above, but on the getitem dim (of a DataFrame)
|
| 403 |
+
index = index_func(5)
|
| 404 |
+
|
| 405 |
+
s = DataFrame(np.random.randn(5, 2), index=index)
|
| 406 |
+
|
| 407 |
+
# setitem
|
| 408 |
+
sc = s.copy()
|
| 409 |
+
sc.loc[idx] = 0
|
| 410 |
+
result = sc.loc[idx].values.ravel()
|
| 411 |
+
assert (result == 0).all()
|
| 412 |
+
|
| 413 |
+
# positional indexing
|
| 414 |
+
msg = (
|
| 415 |
+
"cannot do slice indexing "
|
| 416 |
+
rf"on {type(index).__name__} with these indexers \[(3|4)\.0\] of "
|
| 417 |
+
"type float"
|
| 418 |
+
)
|
| 419 |
+
with pytest.raises(TypeError, match=msg):
|
| 420 |
+
s[idx] = 0
|
| 421 |
+
|
| 422 |
+
with pytest.raises(TypeError, match=msg):
|
| 423 |
+
s[idx]
|
| 424 |
+
|
| 425 |
+
@pytest.mark.parametrize("idx", [slice(3.0, 4), slice(3, 4.0), slice(3.0, 4.0)])
|
| 426 |
+
def test_slice_float(self, idx, frame_or_series, indexer_sl):
|
| 427 |
+
# same as above, but for floats
|
| 428 |
+
index = Index(np.arange(5.0)) + 0.1
|
| 429 |
+
s = gen_obj(frame_or_series, index)
|
| 430 |
+
|
| 431 |
+
expected = s.iloc[3:4]
|
| 432 |
+
|
| 433 |
+
# getitem
|
| 434 |
+
result = indexer_sl(s)[idx]
|
| 435 |
+
assert isinstance(result, type(s))
|
| 436 |
+
tm.assert_equal(result, expected)
|
| 437 |
+
|
| 438 |
+
# setitem
|
| 439 |
+
s2 = s.copy()
|
| 440 |
+
indexer_sl(s2)[idx] = 0
|
| 441 |
+
result = indexer_sl(s2)[idx].values.ravel()
|
| 442 |
+
assert (result == 0).all()
|
| 443 |
+
|
| 444 |
+
def test_floating_index_doc_example(self):
|
| 445 |
+
index = Index([1.5, 2, 3, 4.5, 5])
|
| 446 |
+
s = Series(range(5), index=index)
|
| 447 |
+
assert s[3] == 2
|
| 448 |
+
assert s.loc[3] == 2
|
| 449 |
+
assert s.iloc[3] == 3
|
| 450 |
+
|
| 451 |
+
def test_floating_misc(self, indexer_sl):
|
| 452 |
+
# related 236
|
| 453 |
+
# scalar/slicing of a float index
|
| 454 |
+
s = Series(np.arange(5), index=np.arange(5) * 2.5, dtype=np.int64)
|
| 455 |
+
|
| 456 |
+
# label based slicing
|
| 457 |
+
result = indexer_sl(s)[1.0:3.0]
|
| 458 |
+
expected = Series(1, index=[2.5])
|
| 459 |
+
tm.assert_series_equal(result, expected)
|
| 460 |
+
|
| 461 |
+
# exact indexing when found
|
| 462 |
+
|
| 463 |
+
result = indexer_sl(s)[5.0]
|
| 464 |
+
assert result == 2
|
| 465 |
+
|
| 466 |
+
result = indexer_sl(s)[5]
|
| 467 |
+
assert result == 2
|
| 468 |
+
|
| 469 |
+
# value not found (and no fallbacking at all)
|
| 470 |
+
|
| 471 |
+
# scalar integers
|
| 472 |
+
with pytest.raises(KeyError, match=r"^4$"):
|
| 473 |
+
indexer_sl(s)[4]
|
| 474 |
+
|
| 475 |
+
# fancy floats/integers create the correct entry (as nan)
|
| 476 |
+
# fancy tests
|
| 477 |
+
expected = Series([2, 0], index=Index([5.0, 0.0], dtype=np.float64))
|
| 478 |
+
for fancy_idx in [[5.0, 0.0], np.array([5.0, 0.0])]: # float
|
| 479 |
+
tm.assert_series_equal(indexer_sl(s)[fancy_idx], expected)
|
| 480 |
+
|
| 481 |
+
expected = Series([2, 0], index=Index([5, 0], dtype="float64"))
|
| 482 |
+
for fancy_idx in [[5, 0], np.array([5, 0])]:
|
| 483 |
+
tm.assert_series_equal(indexer_sl(s)[fancy_idx], expected)
|
| 484 |
+
|
| 485 |
+
# all should return the same as we are slicing 'the same'
|
| 486 |
+
result1 = indexer_sl(s)[2:5]
|
| 487 |
+
result2 = indexer_sl(s)[2.0:5.0]
|
| 488 |
+
result3 = indexer_sl(s)[2.0:5]
|
| 489 |
+
result4 = indexer_sl(s)[2.1:5]
|
| 490 |
+
tm.assert_series_equal(result1, result2)
|
| 491 |
+
tm.assert_series_equal(result1, result3)
|
| 492 |
+
tm.assert_series_equal(result1, result4)
|
| 493 |
+
|
| 494 |
+
expected = Series([1, 2], index=[2.5, 5.0])
|
| 495 |
+
result = indexer_sl(s)[2:5]
|
| 496 |
+
|
| 497 |
+
tm.assert_series_equal(result, expected)
|
| 498 |
+
|
| 499 |
+
# list selection
|
| 500 |
+
result1 = indexer_sl(s)[[0.0, 5, 10]]
|
| 501 |
+
result2 = s.iloc[[0, 2, 4]]
|
| 502 |
+
tm.assert_series_equal(result1, result2)
|
| 503 |
+
|
| 504 |
+
with pytest.raises(KeyError, match="not in index"):
|
| 505 |
+
indexer_sl(s)[[1.6, 5, 10]]
|
| 506 |
+
|
| 507 |
+
with pytest.raises(KeyError, match="not in index"):
|
| 508 |
+
indexer_sl(s)[[0, 1, 2]]
|
| 509 |
+
|
| 510 |
+
result = indexer_sl(s)[[2.5, 5]]
|
| 511 |
+
tm.assert_series_equal(result, Series([1, 2], index=[2.5, 5.0]))
|
| 512 |
+
|
| 513 |
+
result = indexer_sl(s)[[2.5]]
|
| 514 |
+
tm.assert_series_equal(result, Series([1], index=[2.5]))
|
| 515 |
+
|
| 516 |
+
def test_floatindex_slicing_bug(self, float_numpy_dtype):
|
| 517 |
+
# GH 5557, related to slicing a float index
|
| 518 |
+
dtype = float_numpy_dtype
|
| 519 |
+
ser = {
|
| 520 |
+
256: 2321.0,
|
| 521 |
+
1: 78.0,
|
| 522 |
+
2: 2716.0,
|
| 523 |
+
3: 0.0,
|
| 524 |
+
4: 369.0,
|
| 525 |
+
5: 0.0,
|
| 526 |
+
6: 269.0,
|
| 527 |
+
7: 0.0,
|
| 528 |
+
8: 0.0,
|
| 529 |
+
9: 0.0,
|
| 530 |
+
10: 3536.0,
|
| 531 |
+
11: 0.0,
|
| 532 |
+
12: 24.0,
|
| 533 |
+
13: 0.0,
|
| 534 |
+
14: 931.0,
|
| 535 |
+
15: 0.0,
|
| 536 |
+
16: 101.0,
|
| 537 |
+
17: 78.0,
|
| 538 |
+
18: 9643.0,
|
| 539 |
+
19: 0.0,
|
| 540 |
+
20: 0.0,
|
| 541 |
+
21: 0.0,
|
| 542 |
+
22: 63761.0,
|
| 543 |
+
23: 0.0,
|
| 544 |
+
24: 446.0,
|
| 545 |
+
25: 0.0,
|
| 546 |
+
26: 34773.0,
|
| 547 |
+
27: 0.0,
|
| 548 |
+
28: 729.0,
|
| 549 |
+
29: 78.0,
|
| 550 |
+
30: 0.0,
|
| 551 |
+
31: 0.0,
|
| 552 |
+
32: 3374.0,
|
| 553 |
+
33: 0.0,
|
| 554 |
+
34: 1391.0,
|
| 555 |
+
35: 0.0,
|
| 556 |
+
36: 361.0,
|
| 557 |
+
37: 0.0,
|
| 558 |
+
38: 61808.0,
|
| 559 |
+
39: 0.0,
|
| 560 |
+
40: 0.0,
|
| 561 |
+
41: 0.0,
|
| 562 |
+
42: 6677.0,
|
| 563 |
+
43: 0.0,
|
| 564 |
+
44: 802.0,
|
| 565 |
+
45: 0.0,
|
| 566 |
+
46: 2691.0,
|
| 567 |
+
47: 0.0,
|
| 568 |
+
48: 3582.0,
|
| 569 |
+
49: 0.0,
|
| 570 |
+
50: 734.0,
|
| 571 |
+
51: 0.0,
|
| 572 |
+
52: 627.0,
|
| 573 |
+
53: 70.0,
|
| 574 |
+
54: 2584.0,
|
| 575 |
+
55: 0.0,
|
| 576 |
+
56: 324.0,
|
| 577 |
+
57: 0.0,
|
| 578 |
+
58: 605.0,
|
| 579 |
+
59: 0.0,
|
| 580 |
+
60: 0.0,
|
| 581 |
+
61: 0.0,
|
| 582 |
+
62: 3989.0,
|
| 583 |
+
63: 10.0,
|
| 584 |
+
64: 42.0,
|
| 585 |
+
65: 0.0,
|
| 586 |
+
66: 904.0,
|
| 587 |
+
67: 0.0,
|
| 588 |
+
68: 88.0,
|
| 589 |
+
69: 70.0,
|
| 590 |
+
70: 8172.0,
|
| 591 |
+
71: 0.0,
|
| 592 |
+
72: 0.0,
|
| 593 |
+
73: 0.0,
|
| 594 |
+
74: 64902.0,
|
| 595 |
+
75: 0.0,
|
| 596 |
+
76: 347.0,
|
| 597 |
+
77: 0.0,
|
| 598 |
+
78: 36605.0,
|
| 599 |
+
79: 0.0,
|
| 600 |
+
80: 379.0,
|
| 601 |
+
81: 70.0,
|
| 602 |
+
82: 0.0,
|
| 603 |
+
83: 0.0,
|
| 604 |
+
84: 3001.0,
|
| 605 |
+
85: 0.0,
|
| 606 |
+
86: 1630.0,
|
| 607 |
+
87: 7.0,
|
| 608 |
+
88: 364.0,
|
| 609 |
+
89: 0.0,
|
| 610 |
+
90: 67404.0,
|
| 611 |
+
91: 9.0,
|
| 612 |
+
92: 0.0,
|
| 613 |
+
93: 0.0,
|
| 614 |
+
94: 7685.0,
|
| 615 |
+
95: 0.0,
|
| 616 |
+
96: 1017.0,
|
| 617 |
+
97: 0.0,
|
| 618 |
+
98: 2831.0,
|
| 619 |
+
99: 0.0,
|
| 620 |
+
100: 2963.0,
|
| 621 |
+
101: 0.0,
|
| 622 |
+
102: 854.0,
|
| 623 |
+
103: 0.0,
|
| 624 |
+
104: 0.0,
|
| 625 |
+
105: 0.0,
|
| 626 |
+
106: 0.0,
|
| 627 |
+
107: 0.0,
|
| 628 |
+
108: 0.0,
|
| 629 |
+
109: 0.0,
|
| 630 |
+
110: 0.0,
|
| 631 |
+
111: 0.0,
|
| 632 |
+
112: 0.0,
|
| 633 |
+
113: 0.0,
|
| 634 |
+
114: 0.0,
|
| 635 |
+
115: 0.0,
|
| 636 |
+
116: 0.0,
|
| 637 |
+
117: 0.0,
|
| 638 |
+
118: 0.0,
|
| 639 |
+
119: 0.0,
|
| 640 |
+
120: 0.0,
|
| 641 |
+
121: 0.0,
|
| 642 |
+
122: 0.0,
|
| 643 |
+
123: 0.0,
|
| 644 |
+
124: 0.0,
|
| 645 |
+
125: 0.0,
|
| 646 |
+
126: 67744.0,
|
| 647 |
+
127: 22.0,
|
| 648 |
+
128: 264.0,
|
| 649 |
+
129: 0.0,
|
| 650 |
+
260: 197.0,
|
| 651 |
+
268: 0.0,
|
| 652 |
+
265: 0.0,
|
| 653 |
+
269: 0.0,
|
| 654 |
+
261: 0.0,
|
| 655 |
+
266: 1198.0,
|
| 656 |
+
267: 0.0,
|
| 657 |
+
262: 2629.0,
|
| 658 |
+
258: 775.0,
|
| 659 |
+
257: 0.0,
|
| 660 |
+
263: 0.0,
|
| 661 |
+
259: 0.0,
|
| 662 |
+
264: 163.0,
|
| 663 |
+
250: 10326.0,
|
| 664 |
+
251: 0.0,
|
| 665 |
+
252: 1228.0,
|
| 666 |
+
253: 0.0,
|
| 667 |
+
254: 2769.0,
|
| 668 |
+
255: 0.0,
|
| 669 |
+
}
|
| 670 |
+
|
| 671 |
+
# smoke test for the repr
|
| 672 |
+
s = Series(ser, dtype=dtype)
|
| 673 |
+
result = s.value_counts()
|
| 674 |
+
assert result.index.dtype == dtype
|
| 675 |
+
str(result)
|
videochat2/lib/python3.10/site-packages/pandas/tests/indexing/test_iat.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
from pandas import (
|
| 4 |
+
DataFrame,
|
| 5 |
+
Series,
|
| 6 |
+
period_range,
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def test_iat(float_frame):
|
| 11 |
+
for i, row in enumerate(float_frame.index):
|
| 12 |
+
for j, col in enumerate(float_frame.columns):
|
| 13 |
+
result = float_frame.iat[i, j]
|
| 14 |
+
expected = float_frame.at[row, col]
|
| 15 |
+
assert result == expected
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_iat_duplicate_columns():
|
| 19 |
+
# https://github.com/pandas-dev/pandas/issues/11754
|
| 20 |
+
df = DataFrame([[1, 2]], columns=["x", "x"])
|
| 21 |
+
assert df.iat[0, 0] == 1
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def test_iat_getitem_series_with_period_index():
|
| 25 |
+
# GH#4390, iat incorrectly indexing
|
| 26 |
+
index = period_range("1/1/2001", periods=10)
|
| 27 |
+
ser = Series(np.random.randn(10), index=index)
|
| 28 |
+
expected = ser[index[0]]
|
| 29 |
+
result = ser.iat[0]
|
| 30 |
+
assert expected == result
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def test_iat_setitem_item_cache_cleared(indexer_ial, using_copy_on_write):
|
| 34 |
+
# GH#45684
|
| 35 |
+
data = {"x": np.arange(8, dtype=np.int64), "y": np.int64(0)}
|
| 36 |
+
df = DataFrame(data).copy()
|
| 37 |
+
ser = df["y"]
|
| 38 |
+
|
| 39 |
+
# previously this iat setting would split the block and fail to clear
|
| 40 |
+
# the item_cache.
|
| 41 |
+
indexer_ial(df)[7, 0] = 9999
|
| 42 |
+
|
| 43 |
+
indexer_ial(df)[7, 1] = 1234
|
| 44 |
+
|
| 45 |
+
assert df.iat[7, 1] == 1234
|
| 46 |
+
if not using_copy_on_write:
|
| 47 |
+
assert ser.iloc[-1] == 1234
|
| 48 |
+
assert df.iloc[-1, -1] == 1234
|