content stringlengths 1 103k ⌀ | path stringlengths 8 216 | filename stringlengths 2 179 | language stringclasses 15
values | size_bytes int64 2 189k | quality_score float64 0.5 0.95 | complexity float64 0 1 | documentation_ratio float64 0 1 | repository stringclasses 5
values | stars int64 0 1k | created_date stringdate 2023-07-10 19:21:08 2025-07-09 19:11:45 | license stringclasses 4
values | is_test bool 2
classes | file_hash stringlengths 32 32 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
import numpy as np\nimport pytest\n\nfrom pandas.errors import (\n PerformanceWarning,\n UnsortedIndexError,\n)\n\nfrom pandas import (\n CategoricalIndex,\n DataFrame,\n Index,\n MultiIndex,\n RangeIndex,\n Series,\n Timestamp,\n)\nimport pandas._testing as tm\nfrom pandas.core.indexes.frozen import FrozenList\n\n\ndef test_sortlevel(idx):\n tuples = list(idx)\n np.random.default_rng(2).shuffle(tuples)\n\n index = MultiIndex.from_tuples(tuples)\n\n sorted_idx, _ = index.sortlevel(0)\n expected = MultiIndex.from_tuples(sorted(tuples))\n assert sorted_idx.equals(expected)\n\n sorted_idx, _ = index.sortlevel(0, ascending=False)\n assert sorted_idx.equals(expected[::-1])\n\n sorted_idx, _ = index.sortlevel(1)\n by1 = sorted(tuples, key=lambda x: (x[1], x[0]))\n expected = MultiIndex.from_tuples(by1)\n assert sorted_idx.equals(expected)\n\n sorted_idx, _ = index.sortlevel(1, ascending=False)\n assert sorted_idx.equals(expected[::-1])\n\n\ndef test_sortlevel_not_sort_remaining():\n mi = MultiIndex.from_tuples([[1, 1, 3], [1, 1, 1]], names=list("ABC"))\n sorted_idx, _ = mi.sortlevel("A", sort_remaining=False)\n assert sorted_idx.equals(mi)\n\n\ndef test_sortlevel_deterministic():\n tuples = [\n ("bar", "one"),\n ("foo", "two"),\n ("qux", "two"),\n ("foo", "one"),\n ("baz", "two"),\n ("qux", "one"),\n ]\n\n index = MultiIndex.from_tuples(tuples)\n\n sorted_idx, _ = index.sortlevel(0)\n expected = MultiIndex.from_tuples(sorted(tuples))\n assert sorted_idx.equals(expected)\n\n sorted_idx, _ = index.sortlevel(0, ascending=False)\n assert sorted_idx.equals(expected[::-1])\n\n sorted_idx, _ = index.sortlevel(1)\n by1 = sorted(tuples, key=lambda x: (x[1], x[0]))\n expected = MultiIndex.from_tuples(by1)\n assert sorted_idx.equals(expected)\n\n sorted_idx, _ = index.sortlevel(1, ascending=False)\n assert sorted_idx.equals(expected[::-1])\n\n\ndef test_sortlevel_na_position():\n # GH#51612\n midx = MultiIndex.from_tuples([(1, np.nan), (1, 1)])\n result = midx.sortlevel(level=[0, 1], na_position="last")[0]\n expected = MultiIndex.from_tuples([(1, 1), (1, np.nan)])\n tm.assert_index_equal(result, expected)\n\n\ndef test_numpy_argsort(idx):\n result = np.argsort(idx)\n expected = idx.argsort()\n tm.assert_numpy_array_equal(result, expected)\n\n # these are the only two types that perform\n # pandas compatibility input validation - the\n # rest already perform separate (or no) such\n # validation via their 'values' attribute as\n # defined in pandas.core.indexes/base.py - they\n # cannot be changed at the moment due to\n # backwards compatibility concerns\n if isinstance(type(idx), (CategoricalIndex, RangeIndex)):\n msg = "the 'axis' parameter is not supported"\n with pytest.raises(ValueError, match=msg):\n np.argsort(idx, axis=1)\n\n msg = "the 'kind' parameter is not supported"\n with pytest.raises(ValueError, match=msg):\n np.argsort(idx, kind="mergesort")\n\n msg = "the 'order' parameter is not supported"\n with pytest.raises(ValueError, match=msg):\n np.argsort(idx, order=("a", "b"))\n\n\ndef test_unsortedindex():\n # GH 11897\n mi = MultiIndex.from_tuples(\n [("z", "a"), ("x", "a"), ("y", "b"), ("x", "b"), ("y", "a"), ("z", "b")],\n names=["one", "two"],\n )\n df = DataFrame([[i, 10 * i] for i in range(6)], index=mi, columns=["one", "two"])\n\n # GH 16734: not sorted, but no real slicing\n result = df.loc(axis=0)["z", "a"]\n expected = df.iloc[0]\n tm.assert_series_equal(result, expected)\n\n msg = (\n "MultiIndex slicing requires the index to be lexsorted: "\n r"slicing on levels \[1\], lexsort depth 0"\n )\n with pytest.raises(UnsortedIndexError, match=msg):\n df.loc(axis=0)["z", slice("a")]\n df.sort_index(inplace=True)\n assert len(df.loc(axis=0)["z", :]) == 2\n\n with pytest.raises(KeyError, match="'q'"):\n df.loc(axis=0)["q", :]\n\n\ndef test_unsortedindex_doc_examples():\n # https://pandas.pydata.org/pandas-docs/stable/advanced.html#sorting-a-multiindex\n dfm = DataFrame(\n {\n "jim": [0, 0, 1, 1],\n "joe": ["x", "x", "z", "y"],\n "jolie": np.random.default_rng(2).random(4),\n }\n )\n\n dfm = dfm.set_index(["jim", "joe"])\n with tm.assert_produces_warning(PerformanceWarning):\n dfm.loc[(1, "z")]\n\n msg = r"Key length \(2\) was greater than MultiIndex lexsort depth \(1\)"\n with pytest.raises(UnsortedIndexError, match=msg):\n dfm.loc[(0, "y"):(1, "z")]\n\n assert not dfm.index._is_lexsorted()\n assert dfm.index._lexsort_depth == 1\n\n # sort it\n dfm = dfm.sort_index()\n dfm.loc[(1, "z")]\n dfm.loc[(0, "y"):(1, "z")]\n\n assert dfm.index._is_lexsorted()\n assert dfm.index._lexsort_depth == 2\n\n\ndef test_reconstruct_sort():\n # starts off lexsorted & monotonic\n mi = MultiIndex.from_arrays([["A", "A", "B", "B", "B"], [1, 2, 1, 2, 3]])\n assert mi.is_monotonic_increasing\n recons = mi._sort_levels_monotonic()\n assert recons.is_monotonic_increasing\n assert mi is recons\n\n assert mi.equals(recons)\n assert Index(mi.values).equals(Index(recons.values))\n\n # cannot convert to lexsorted\n mi = MultiIndex.from_tuples(\n [("z", "a"), ("x", "a"), ("y", "b"), ("x", "b"), ("y", "a"), ("z", "b")],\n names=["one", "two"],\n )\n assert not mi.is_monotonic_increasing\n recons = mi._sort_levels_monotonic()\n assert not recons.is_monotonic_increasing\n assert mi.equals(recons)\n assert Index(mi.values).equals(Index(recons.values))\n\n # cannot convert to lexsorted\n mi = MultiIndex(\n levels=[["b", "d", "a"], [1, 2, 3]],\n codes=[[0, 1, 0, 2], [2, 0, 0, 1]],\n names=["col1", "col2"],\n )\n assert not mi.is_monotonic_increasing\n recons = mi._sort_levels_monotonic()\n assert not recons.is_monotonic_increasing\n assert mi.equals(recons)\n assert Index(mi.values).equals(Index(recons.values))\n\n\ndef test_reconstruct_remove_unused():\n # xref to GH 2770\n df = DataFrame(\n [["deleteMe", 1, 9], ["keepMe", 2, 9], ["keepMeToo", 3, 9]],\n columns=["first", "second", "third"],\n )\n df2 = df.set_index(["first", "second"], drop=False)\n df2 = df2[df2["first"] != "deleteMe"]\n\n # removed levels are there\n expected = MultiIndex(\n levels=[["deleteMe", "keepMe", "keepMeToo"], [1, 2, 3]],\n codes=[[1, 2], [1, 2]],\n names=["first", "second"],\n )\n result = df2.index\n tm.assert_index_equal(result, expected)\n\n expected = MultiIndex(\n levels=[["keepMe", "keepMeToo"], [2, 3]],\n codes=[[0, 1], [0, 1]],\n names=["first", "second"],\n )\n result = df2.index.remove_unused_levels()\n tm.assert_index_equal(result, expected)\n\n # idempotent\n result2 = result.remove_unused_levels()\n tm.assert_index_equal(result2, expected)\n assert result2.is_(result)\n\n\n@pytest.mark.parametrize(\n "first_type,second_type", [("int64", "int64"), ("datetime64[D]", "str")]\n)\ndef test_remove_unused_levels_large(first_type, second_type):\n # GH16556\n\n # because tests should be deterministic (and this test in particular\n # checks that levels are removed, which is not the case for every\n # random input):\n rng = np.random.default_rng(10) # seed is arbitrary value that works\n\n size = 1 << 16\n df = DataFrame(\n {\n "first": rng.integers(0, 1 << 13, size).astype(first_type),\n "second": rng.integers(0, 1 << 10, size).astype(second_type),\n "third": rng.random(size),\n }\n )\n df = df.groupby(["first", "second"]).sum()\n df = df[df.third < 0.1]\n\n result = df.index.remove_unused_levels()\n assert len(result.levels[0]) < len(df.index.levels[0])\n assert len(result.levels[1]) < len(df.index.levels[1])\n assert result.equals(df.index)\n\n expected = df.reset_index().set_index(["first", "second"]).index\n tm.assert_index_equal(result, expected)\n\n\n@pytest.mark.parametrize("level0", [["a", "d", "b"], ["a", "d", "b", "unused"]])\n@pytest.mark.parametrize(\n "level1", [["w", "x", "y", "z"], ["w", "x", "y", "z", "unused"]]\n)\ndef test_remove_unused_nan(level0, level1):\n # GH 18417\n mi = MultiIndex(levels=[level0, level1], codes=[[0, 2, -1, 1, -1], [0, 1, 2, 3, 2]])\n\n result = mi.remove_unused_levels()\n tm.assert_index_equal(result, mi)\n for level in 0, 1:\n assert "unused" not in result.levels[level]\n\n\ndef test_argsort(idx):\n result = idx.argsort()\n expected = idx.values.argsort()\n tm.assert_numpy_array_equal(result, expected)\n\n\ndef test_remove_unused_levels_with_nan():\n # GH 37510\n idx = Index([(1, np.nan), (3, 4)]).rename(["id1", "id2"])\n idx = idx.set_levels(["a", np.nan], level="id1")\n idx = idx.remove_unused_levels()\n result = idx.levels\n expected = FrozenList([["a", np.nan], [4]])\n assert str(result) == str(expected)\n\n\ndef test_sort_values_nan():\n # GH48495, GH48626\n midx = MultiIndex(levels=[["A", "B", "C"], ["D"]], codes=[[1, 0, 2], [-1, -1, 0]])\n result = midx.sort_values()\n expected = MultiIndex(\n levels=[["A", "B", "C"], ["D"]], codes=[[0, 1, 2], [-1, -1, 0]]\n )\n tm.assert_index_equal(result, expected)\n\n\ndef test_sort_values_incomparable():\n # GH48495\n mi = MultiIndex.from_arrays(\n [\n [1, Timestamp("2000-01-01")],\n [3, 4],\n ]\n )\n match = "'<' not supported between instances of 'Timestamp' and 'int'"\n with pytest.raises(TypeError, match=match):\n mi.sort_values()\n\n\n@pytest.mark.parametrize("na_position", ["first", "last"])\n@pytest.mark.parametrize("dtype", ["float64", "Int64", "Float64"])\ndef test_sort_values_with_na_na_position(dtype, na_position):\n # 51612\n arrays = [\n Series([1, 1, 2], dtype=dtype),\n Series([1, None, 3], dtype=dtype),\n ]\n index = MultiIndex.from_arrays(arrays)\n result = index.sort_values(na_position=na_position)\n if na_position == "first":\n arrays = [\n Series([1, 1, 2], dtype=dtype),\n Series([None, 1, 3], dtype=dtype),\n ]\n else:\n arrays = [\n Series([1, 1, 2], dtype=dtype),\n Series([1, None, 3], dtype=dtype),\n ]\n expected = MultiIndex.from_arrays(arrays)\n tm.assert_index_equal(result, expected)\n\n\ndef test_sort_unnecessary_warning():\n # GH#55386\n midx = MultiIndex.from_tuples([(1.5, 2), (3.5, 3), (0, 1)])\n midx = midx.set_levels([2.5, np.nan, 1], level=0)\n result = midx.sort_values()\n expected = MultiIndex.from_tuples([(1, 3), (2.5, 1), (np.nan, 2)])\n tm.assert_index_equal(result, expected)\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\test_sorting.py | test_sorting.py | Python | 10,745 | 0.95 | 0.063037 | 0.099644 | awesome-app | 88 | 2025-02-09T02:09:50.032687 | GPL-3.0 | true | 4e429fabf8e4a282319b461f24c42193 |
import numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\n\n\ndef test_take(idx):\n indexer = [4, 3, 0, 2]\n result = idx.take(indexer)\n expected = idx[indexer]\n assert result.equals(expected)\n\n # GH 10791\n msg = "'MultiIndex' object has no attribute 'freq'"\n with pytest.raises(AttributeError, match=msg):\n idx.freq\n\n\ndef test_take_invalid_kwargs(idx):\n indices = [1, 2]\n\n msg = r"take\(\) got an unexpected keyword argument 'foo'"\n with pytest.raises(TypeError, match=msg):\n idx.take(indices, foo=2)\n\n msg = "the 'out' parameter is not supported"\n with pytest.raises(ValueError, match=msg):\n idx.take(indices, out=indices)\n\n msg = "the 'mode' parameter is not supported"\n with pytest.raises(ValueError, match=msg):\n idx.take(indices, mode="clip")\n\n\ndef test_take_fill_value():\n # GH 12631\n vals = [["A", "B"], [pd.Timestamp("2011-01-01"), pd.Timestamp("2011-01-02")]]\n idx = pd.MultiIndex.from_product(vals, names=["str", "dt"])\n\n result = idx.take(np.array([1, 0, -1]))\n exp_vals = [\n ("A", pd.Timestamp("2011-01-02")),\n ("A", pd.Timestamp("2011-01-01")),\n ("B", pd.Timestamp("2011-01-02")),\n ]\n expected = pd.MultiIndex.from_tuples(exp_vals, names=["str", "dt"])\n tm.assert_index_equal(result, expected)\n\n # fill_value\n result = idx.take(np.array([1, 0, -1]), fill_value=True)\n exp_vals = [\n ("A", pd.Timestamp("2011-01-02")),\n ("A", pd.Timestamp("2011-01-01")),\n (np.nan, pd.NaT),\n ]\n expected = pd.MultiIndex.from_tuples(exp_vals, names=["str", "dt"])\n tm.assert_index_equal(result, expected)\n\n # allow_fill=False\n result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True)\n exp_vals = [\n ("A", pd.Timestamp("2011-01-02")),\n ("A", pd.Timestamp("2011-01-01")),\n ("B", pd.Timestamp("2011-01-02")),\n ]\n expected = pd.MultiIndex.from_tuples(exp_vals, names=["str", "dt"])\n tm.assert_index_equal(result, expected)\n\n msg = "When allow_fill=True and fill_value is not None, all indices must be >= -1"\n with pytest.raises(ValueError, match=msg):\n idx.take(np.array([1, 0, -2]), fill_value=True)\n with pytest.raises(ValueError, match=msg):\n idx.take(np.array([1, 0, -5]), fill_value=True)\n\n msg = "index -5 is out of bounds for( axis 0 with)? size 4"\n with pytest.raises(IndexError, match=msg):\n idx.take(np.array([1, -5]))\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\test_take.py | test_take.py | Python | 2,487 | 0.95 | 0.051282 | 0.064516 | vue-tools | 71 | 2024-06-05T16:14:34.192483 | GPL-3.0 | true | b6d4ac63907309ceacdfe29c91b5ec20 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\__pycache__\conftest.cpython-313.pyc | conftest.cpython-313.pyc | Other | 988 | 0.8 | 0 | 0 | python-kit | 476 | 2024-01-19T03:03:23.489044 | MIT | true | 623cf3499a34a489fc5e03884920fa1e |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\__pycache__\test_analytics.cpython-313.pyc | test_analytics.cpython-313.pyc | Other | 12,255 | 0.8 | 0.010989 | 0.006061 | awesome-app | 481 | 2024-05-31T03:56:09.148457 | Apache-2.0 | true | 48b18ea909ae621b476156bdb491cf6a |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\__pycache__\test_astype.cpython-313.pyc | test_astype.cpython-313.pyc | Other | 2,084 | 0.8 | 0 | 0 | node-utils | 566 | 2024-07-31T20:20:33.280545 | GPL-3.0 | true | 6b338bcbc8ca8618243e6b912d10a43e |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\__pycache__\test_compat.cpython-313.pyc | test_compat.cpython-313.pyc | Other | 6,268 | 0.8 | 0 | 0.011111 | python-kit | 782 | 2023-10-26T06:27:38.615001 | GPL-3.0 | true | b8a21a96f2fd8f7461b5202ca5b30664 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\__pycache__\test_constructors.cpython-313.pyc | test_constructors.cpython-313.pyc | Other | 41,018 | 0.95 | 0.002079 | 0.067686 | python-kit | 66 | 2024-03-25T15:50:20.782673 | Apache-2.0 | true | 7323d6537e3bf1103fe06ce46b9251f7 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\__pycache__\test_conversion.cpython-313.pyc | test_conversion.cpython-313.pyc | Other | 8,476 | 0.8 | 0 | 0.009174 | node-utils | 794 | 2024-01-21T13:27:14.373492 | BSD-3-Clause | true | bdcdea4916c0670cd4d107c8ce89f69c |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\__pycache__\test_copy.cpython-313.pyc | test_copy.cpython-313.pyc | Other | 3,978 | 0.8 | 0 | 0 | python-kit | 458 | 2023-08-30T05:14:31.962741 | GPL-3.0 | true | e0ff347c9dea7d72493025b8bac19165 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\__pycache__\test_drop.cpython-313.pyc | test_drop.cpython-313.pyc | Other | 10,593 | 0.8 | 0 | 0 | node-utils | 971 | 2025-03-07T12:44:59.010262 | Apache-2.0 | true | 2d2b0b90ef292cf87330a3e619f2a6ef |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\__pycache__\test_duplicates.cpython-313.pyc | test_duplicates.cpython-313.pyc | Other | 18,319 | 0.8 | 0 | 0.043243 | vue-tools | 515 | 2024-04-18T01:28:54.339498 | Apache-2.0 | true | 66ec5b2a4af73a04b711fcfb05a1dd69 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\__pycache__\test_equivalence.cpython-313.pyc | test_equivalence.cpython-313.pyc | Other | 14,753 | 0.8 | 0 | 0 | awesome-app | 661 | 2024-02-04T23:25:56.016183 | Apache-2.0 | true | 29d743aac4e0b920f9b6fbbf1ac04831 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\__pycache__\test_formats.cpython-313.pyc | test_formats.cpython-313.pyc | Other | 13,551 | 0.8 | 0 | 0.048387 | python-kit | 434 | 2025-03-10T22:21:56.030475 | BSD-3-Clause | true | e0fe4a76b2c0190c2530a69e29e2fb99 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\__pycache__\test_get_level_values.cpython-313.pyc | test_get_level_values.cpython-313.pyc | Other | 7,499 | 0.8 | 0 | 0.220779 | react-lib | 227 | 2023-07-19T08:16:05.649931 | MIT | true | 80867ad4880478a3baf596e2aea003db |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\__pycache__\test_get_set.cpython-313.pyc | test_get_set.cpython-313.pyc | Other | 20,036 | 0.8 | 0 | 0 | node-utils | 547 | 2023-11-03T08:34:21.568385 | Apache-2.0 | true | 8ef2f72f357d22005e9a69cc71d5079e |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\__pycache__\test_indexing.cpython-313.pyc | test_indexing.cpython-313.pyc | Other | 55,419 | 0.6 | 0.00823 | 0.015759 | vue-tools | 888 | 2024-06-03T06:51:13.670419 | BSD-3-Clause | true | b0a98c1e1c00bb7b2f69ed4c2510f758 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\__pycache__\test_integrity.cpython-313.pyc | test_integrity.cpython-313.pyc | Other | 16,690 | 0.8 | 0.004444 | 0.009346 | awesome-app | 439 | 2023-07-26T02:23:59.795022 | GPL-3.0 | true | e395da2e88768d14d621909f14745143 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\__pycache__\test_isin.cpython-313.pyc | test_isin.cpython-313.pyc | Other | 6,929 | 0.8 | 0 | 0.021505 | react-lib | 472 | 2023-07-13T14:37:49.473866 | BSD-3-Clause | true | 621a7ea02b2767bba2bd25ef9b304fa2 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\__pycache__\test_join.cpython-313.pyc | test_join.cpython-313.pyc | Other | 12,830 | 0.8 | 0 | 0.039063 | vue-tools | 424 | 2025-04-16T04:36:09.588938 | GPL-3.0 | true | 5bdb1f7a355f0657a6c2e98f32939837 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\__pycache__\test_lexsort.cpython-313.pyc | test_lexsort.cpython-313.pyc | Other | 2,121 | 0.8 | 0 | 0 | awesome-app | 505 | 2024-12-16T06:54:37.288249 | GPL-3.0 | true | 642cb35c54345db848b525eabaeb7633 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\__pycache__\test_missing.cpython-313.pyc | test_missing.cpython-313.pyc | Other | 6,358 | 0.8 | 0.012346 | 0.013889 | node-utils | 211 | 2023-09-19T05:00:36.494096 | MIT | true | 7b1a85510538be637c886f44ccc38e8d |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\__pycache__\test_monotonic.cpython-313.pyc | test_monotonic.cpython-313.pyc | Other | 9,474 | 0.8 | 0 | 0 | awesome-app | 134 | 2023-10-13T14:02:43.046173 | MIT | true | 3c7fc11499559fb2eca7a722c49cd705 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\__pycache__\test_names.cpython-313.pyc | test_names.cpython-313.pyc | Other | 11,308 | 0.8 | 0.013423 | 0 | react-lib | 650 | 2025-02-22T14:52:34.241508 | Apache-2.0 | true | 01dce3d8bca09adc8edd53e90b6365b5 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\__pycache__\test_partial_indexing.cpython-313.pyc | test_partial_indexing.cpython-313.pyc | Other | 6,232 | 0.8 | 0 | 0.015625 | python-kit | 576 | 2023-12-26T20:56:01.391998 | BSD-3-Clause | true | 4f5f72e1455ef7aba36a5b6a77fed941 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\__pycache__\test_pickle.cpython-313.pyc | test_pickle.cpython-313.pyc | Other | 623 | 0.7 | 0 | 0 | vue-tools | 705 | 2023-08-20T10:08:04.074578 | GPL-3.0 | true | 4bd88a005e218e58cf0dd052cbd1ce1c |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\__pycache__\test_reindex.cpython-313.pyc | test_reindex.cpython-313.pyc | Other | 11,267 | 0.8 | 0.009615 | 0.041667 | python-kit | 924 | 2023-11-20T22:59:36.343862 | GPL-3.0 | true | 6d4b81cd3122adf04bd527a291884c13 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\__pycache__\test_reshape.cpython-313.pyc | test_reshape.cpython-313.pyc | Other | 11,942 | 0.8 | 0.007353 | 0.022901 | node-utils | 541 | 2024-06-14T22:54:58.444032 | MIT | true | 312b513137fafe5ef6bbe15ca7e95e67 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\__pycache__\test_setops.cpython-313.pyc | test_setops.cpython-313.pyc | Other | 39,058 | 0.8 | 0.001953 | 0.010707 | node-utils | 598 | 2025-01-02T19:22:31.657612 | Apache-2.0 | true | e48092e5f13553e351c1e08d69f30768 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\__pycache__\test_sorting.cpython-313.pyc | test_sorting.cpython-313.pyc | Other | 17,705 | 0.95 | 0 | 0.016129 | vue-tools | 48 | 2025-06-15T07:18:17.686569 | BSD-3-Clause | true | db7ef8281a88606b546aeaae1e2a2c6b |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\__pycache__\test_take.cpython-313.pyc | test_take.cpython-313.pyc | Other | 4,788 | 0.8 | 0.015625 | 0 | python-kit | 470 | 2024-02-14T21:03:00.675016 | BSD-3-Clause | true | fedf7a6401489e3884a2bedb3e7a22fb |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\multi\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 201 | 0.7 | 0 | 0 | vue-tools | 530 | 2025-01-23T03:51:12.877789 | Apache-2.0 | true | 40d7cdd19ea0a7685c2e1f8215429948 |
import numpy as np\nimport pytest\n\nfrom pandas import (\n Index,\n to_datetime,\n to_timedelta,\n)\nimport pandas._testing as tm\n\n\nclass TestAstype:\n def test_astype_float64_to_uint64(self):\n # GH#45309 used to incorrectly return Index with int64 dtype\n idx = Index([0.0, 5.0, 10.0, 15.0, 20.0], dtype=np.float64)\n result = idx.astype("u8")\n expected = Index([0, 5, 10, 15, 20], dtype=np.uint64)\n tm.assert_index_equal(result, expected, exact=True)\n\n idx_with_negatives = idx - 10\n with pytest.raises(ValueError, match="losslessly"):\n idx_with_negatives.astype(np.uint64)\n\n def test_astype_float64_to_object(self):\n float_index = Index([0.0, 2.5, 5.0, 7.5, 10.0], dtype=np.float64)\n result = float_index.astype(object)\n assert result.equals(float_index)\n assert float_index.equals(result)\n assert isinstance(result, Index) and result.dtype == object\n\n def test_astype_float64_mixed_to_object(self):\n # mixed int-float\n idx = Index([1.5, 2, 3, 4, 5], dtype=np.float64)\n idx.name = "foo"\n result = idx.astype(object)\n assert result.equals(idx)\n assert idx.equals(result)\n assert isinstance(result, Index) and result.dtype == object\n\n @pytest.mark.parametrize("dtype", ["int16", "int32", "int64"])\n def test_astype_float64_to_int_dtype(self, dtype):\n # GH#12881\n # a float astype int\n idx = Index([0, 1, 2], dtype=np.float64)\n result = idx.astype(dtype)\n expected = Index([0, 1, 2], dtype=dtype)\n tm.assert_index_equal(result, expected, exact=True)\n\n idx = Index([0, 1.1, 2], dtype=np.float64)\n result = idx.astype(dtype)\n expected = Index([0, 1, 2], dtype=dtype)\n tm.assert_index_equal(result, expected, exact=True)\n\n @pytest.mark.parametrize("dtype", ["float32", "float64"])\n def test_astype_float64_to_float_dtype(self, dtype):\n # GH#12881\n # a float astype int\n idx = Index([0, 1, 2], dtype=np.float64)\n result = idx.astype(dtype)\n assert isinstance(result, Index) and result.dtype == dtype\n\n @pytest.mark.parametrize("dtype", ["M8[ns]", "m8[ns]"])\n def test_astype_float_to_datetimelike(self, dtype):\n # GH#49660 pre-2.0 Index.astype from floating to M8/m8/Period raised,\n # inconsistent with Series.astype\n idx = Index([0, 1.1, 2], dtype=np.float64)\n\n result = idx.astype(dtype)\n if dtype[0] == "M":\n expected = to_datetime(idx.values)\n else:\n expected = to_timedelta(idx.values)\n tm.assert_index_equal(result, expected)\n\n # check that we match Series behavior\n result = idx.to_series().set_axis(range(3)).astype(dtype)\n expected = expected.to_series().set_axis(range(3))\n tm.assert_series_equal(result, expected)\n\n @pytest.mark.parametrize("dtype", [int, "int16", "int32", "int64"])\n @pytest.mark.parametrize("non_finite", [np.inf, np.nan])\n def test_cannot_cast_inf_to_int(self, non_finite, dtype):\n # GH#13149\n idx = Index([1, 2, non_finite], dtype=np.float64)\n\n msg = r"Cannot convert non-finite values \(NA or inf\) to integer"\n with pytest.raises(ValueError, match=msg):\n idx.astype(dtype)\n\n def test_astype_from_object(self):\n index = Index([1.0, np.nan, 0.2], dtype="object")\n result = index.astype(float)\n expected = Index([1.0, np.nan, 0.2], dtype=np.float64)\n assert result.dtype == expected.dtype\n tm.assert_index_equal(result, expected)\n | .venv\Lib\site-packages\pandas\tests\indexes\numeric\test_astype.py | test_astype.py | Python | 3,618 | 0.95 | 0.105263 | 0.125 | node-utils | 259 | 2024-12-12T19:59:09.768271 | Apache-2.0 | true | 492299dbdf6eeef8eb0e7b2b95480d70 |
import numpy as np\nimport pytest\n\nfrom pandas.errors import InvalidIndexError\n\nfrom pandas import (\n NA,\n Index,\n RangeIndex,\n Series,\n Timestamp,\n)\nimport pandas._testing as tm\nfrom pandas.core.arrays import (\n ArrowExtensionArray,\n FloatingArray,\n)\n\n\n@pytest.fixture\ndef index_large():\n # large values used in Index[uint64] tests where no compat needed with Int64/Float64\n large = [2**63, 2**63 + 10, 2**63 + 15, 2**63 + 20, 2**63 + 25]\n return Index(large, dtype=np.uint64)\n\n\nclass TestGetLoc:\n def test_get_loc(self):\n index = Index([0, 1, 2])\n assert index.get_loc(1) == 1\n\n def test_get_loc_raises_bad_label(self):\n index = Index([0, 1, 2])\n with pytest.raises(InvalidIndexError, match=r"\[1, 2\]"):\n index.get_loc([1, 2])\n\n def test_get_loc_float64(self):\n idx = Index([0.0, 1.0, 2.0], dtype=np.float64)\n\n with pytest.raises(KeyError, match="^'foo'$"):\n idx.get_loc("foo")\n with pytest.raises(KeyError, match=r"^1\.5$"):\n idx.get_loc(1.5)\n with pytest.raises(KeyError, match="^True$"):\n idx.get_loc(True)\n with pytest.raises(KeyError, match="^False$"):\n idx.get_loc(False)\n\n def test_get_loc_na(self):\n idx = Index([np.nan, 1, 2], dtype=np.float64)\n assert idx.get_loc(1) == 1\n assert idx.get_loc(np.nan) == 0\n\n idx = Index([np.nan, 1, np.nan], dtype=np.float64)\n assert idx.get_loc(1) == 1\n\n # representable by slice [0:2:2]\n msg = "'Cannot get left slice bound for non-unique label: nan'"\n with pytest.raises(KeyError, match=msg):\n idx.slice_locs(np.nan)\n # not representable by slice\n idx = Index([np.nan, 1, np.nan, np.nan], dtype=np.float64)\n assert idx.get_loc(1) == 1\n msg = "'Cannot get left slice bound for non-unique label: nan"\n with pytest.raises(KeyError, match=msg):\n idx.slice_locs(np.nan)\n\n def test_get_loc_missing_nan(self):\n # GH#8569\n idx = Index([1, 2], dtype=np.float64)\n assert idx.get_loc(1) == 0\n with pytest.raises(KeyError, match=r"^3$"):\n idx.get_loc(3)\n with pytest.raises(KeyError, match="^nan$"):\n idx.get_loc(np.nan)\n with pytest.raises(InvalidIndexError, match=r"\[nan\]"):\n # listlike/non-hashable raises TypeError\n idx.get_loc([np.nan])\n\n @pytest.mark.parametrize("vals", [[1], [1.0], [Timestamp("2019-12-31")], ["test"]])\n def test_get_loc_float_index_nan_with_method(self, vals):\n # GH#39382\n idx = Index(vals)\n with pytest.raises(KeyError, match="nan"):\n idx.get_loc(np.nan)\n\n @pytest.mark.parametrize("dtype", ["f8", "i8", "u8"])\n def test_get_loc_numericindex_none_raises(self, dtype):\n # case that goes through searchsorted and key is non-comparable to values\n arr = np.arange(10**7, dtype=dtype)\n idx = Index(arr)\n with pytest.raises(KeyError, match="None"):\n idx.get_loc(None)\n\n def test_get_loc_overflows(self):\n # unique but non-monotonic goes through IndexEngine.mapping.get_item\n idx = Index([0, 2, 1])\n\n val = np.iinfo(np.int64).max + 1\n\n with pytest.raises(KeyError, match=str(val)):\n idx.get_loc(val)\n with pytest.raises(KeyError, match=str(val)):\n idx._engine.get_loc(val)\n\n\nclass TestGetIndexer:\n def test_get_indexer(self):\n index1 = Index([1, 2, 3, 4, 5])\n index2 = Index([2, 4, 6])\n\n r1 = index1.get_indexer(index2)\n e1 = np.array([1, 3, -1], dtype=np.intp)\n tm.assert_almost_equal(r1, e1)\n\n @pytest.mark.parametrize("reverse", [True, False])\n @pytest.mark.parametrize(\n "expected,method",\n [\n (np.array([-1, 0, 0, 1, 1], dtype=np.intp), "pad"),\n (np.array([-1, 0, 0, 1, 1], dtype=np.intp), "ffill"),\n (np.array([0, 0, 1, 1, 2], dtype=np.intp), "backfill"),\n (np.array([0, 0, 1, 1, 2], dtype=np.intp), "bfill"),\n ],\n )\n def test_get_indexer_methods(self, reverse, expected, method):\n index1 = Index([1, 2, 3, 4, 5])\n index2 = Index([2, 4, 6])\n\n if reverse:\n index1 = index1[::-1]\n expected = expected[::-1]\n\n result = index2.get_indexer(index1, method=method)\n tm.assert_almost_equal(result, expected)\n\n def test_get_indexer_invalid(self):\n # GH10411\n index = Index(np.arange(10))\n\n with pytest.raises(ValueError, match="tolerance argument"):\n index.get_indexer([1, 0], tolerance=1)\n\n with pytest.raises(ValueError, match="limit argument"):\n index.get_indexer([1, 0], limit=1)\n\n @pytest.mark.parametrize(\n "method, tolerance, indexer, expected",\n [\n ("pad", None, [0, 5, 9], [0, 5, 9]),\n ("backfill", None, [0, 5, 9], [0, 5, 9]),\n ("nearest", None, [0, 5, 9], [0, 5, 9]),\n ("pad", 0, [0, 5, 9], [0, 5, 9]),\n ("backfill", 0, [0, 5, 9], [0, 5, 9]),\n ("nearest", 0, [0, 5, 9], [0, 5, 9]),\n ("pad", None, [0.2, 1.8, 8.5], [0, 1, 8]),\n ("backfill", None, [0.2, 1.8, 8.5], [1, 2, 9]),\n ("nearest", None, [0.2, 1.8, 8.5], [0, 2, 9]),\n ("pad", 1, [0.2, 1.8, 8.5], [0, 1, 8]),\n ("backfill", 1, [0.2, 1.8, 8.5], [1, 2, 9]),\n ("nearest", 1, [0.2, 1.8, 8.5], [0, 2, 9]),\n ("pad", 0.2, [0.2, 1.8, 8.5], [0, -1, -1]),\n ("backfill", 0.2, [0.2, 1.8, 8.5], [-1, 2, -1]),\n ("nearest", 0.2, [0.2, 1.8, 8.5], [0, 2, -1]),\n ],\n )\n def test_get_indexer_nearest(self, method, tolerance, indexer, expected):\n index = Index(np.arange(10))\n\n actual = index.get_indexer(indexer, method=method, tolerance=tolerance)\n tm.assert_numpy_array_equal(actual, np.array(expected, dtype=np.intp))\n\n @pytest.mark.parametrize("listtype", [list, tuple, Series, np.array])\n @pytest.mark.parametrize(\n "tolerance, expected",\n list(\n zip(\n [[0.3, 0.3, 0.1], [0.2, 0.1, 0.1], [0.1, 0.5, 0.5]],\n [[0, 2, -1], [0, -1, -1], [-1, 2, 9]],\n )\n ),\n )\n def test_get_indexer_nearest_listlike_tolerance(\n self, tolerance, expected, listtype\n ):\n index = Index(np.arange(10))\n\n actual = index.get_indexer(\n [0.2, 1.8, 8.5], method="nearest", tolerance=listtype(tolerance)\n )\n tm.assert_numpy_array_equal(actual, np.array(expected, dtype=np.intp))\n\n def test_get_indexer_nearest_error(self):\n index = Index(np.arange(10))\n with pytest.raises(ValueError, match="limit argument"):\n index.get_indexer([1, 0], method="nearest", limit=1)\n\n with pytest.raises(ValueError, match="tolerance size must match"):\n index.get_indexer([1, 0], method="nearest", tolerance=[1, 2, 3])\n\n @pytest.mark.parametrize(\n "method,expected",\n [("pad", [8, 7, 0]), ("backfill", [9, 8, 1]), ("nearest", [9, 7, 0])],\n )\n def test_get_indexer_nearest_decreasing(self, method, expected):\n index = Index(np.arange(10))[::-1]\n\n actual = index.get_indexer([0, 5, 9], method=method)\n tm.assert_numpy_array_equal(actual, np.array([9, 4, 0], dtype=np.intp))\n\n actual = index.get_indexer([0.2, 1.8, 8.5], method=method)\n tm.assert_numpy_array_equal(actual, np.array(expected, dtype=np.intp))\n\n @pytest.mark.parametrize("idx_dtype", ["int64", "float64", "uint64", "range"])\n @pytest.mark.parametrize("method", ["get_indexer", "get_indexer_non_unique"])\n def test_get_indexer_numeric_index_boolean_target(self, method, idx_dtype):\n # GH 16877\n\n if idx_dtype == "range":\n numeric_index = RangeIndex(4)\n else:\n numeric_index = Index(np.arange(4, dtype=idx_dtype))\n\n other = Index([True, False, True])\n\n result = getattr(numeric_index, method)(other)\n expected = np.array([-1, -1, -1], dtype=np.intp)\n if method == "get_indexer":\n tm.assert_numpy_array_equal(result, expected)\n else:\n missing = np.arange(3, dtype=np.intp)\n tm.assert_numpy_array_equal(result[0], expected)\n tm.assert_numpy_array_equal(result[1], missing)\n\n @pytest.mark.parametrize("method", ["pad", "backfill", "nearest"])\n def test_get_indexer_with_method_numeric_vs_bool(self, method):\n left = Index([1, 2, 3])\n right = Index([True, False])\n\n with pytest.raises(TypeError, match="Cannot compare"):\n left.get_indexer(right, method=method)\n\n with pytest.raises(TypeError, match="Cannot compare"):\n right.get_indexer(left, method=method)\n\n def test_get_indexer_numeric_vs_bool(self):\n left = Index([1, 2, 3])\n right = Index([True, False])\n\n res = left.get_indexer(right)\n expected = -1 * np.ones(len(right), dtype=np.intp)\n tm.assert_numpy_array_equal(res, expected)\n\n res = right.get_indexer(left)\n expected = -1 * np.ones(len(left), dtype=np.intp)\n tm.assert_numpy_array_equal(res, expected)\n\n res = left.get_indexer_non_unique(right)[0]\n expected = -1 * np.ones(len(right), dtype=np.intp)\n tm.assert_numpy_array_equal(res, expected)\n\n res = right.get_indexer_non_unique(left)[0]\n expected = -1 * np.ones(len(left), dtype=np.intp)\n tm.assert_numpy_array_equal(res, expected)\n\n def test_get_indexer_float64(self):\n idx = Index([0.0, 1.0, 2.0], dtype=np.float64)\n tm.assert_numpy_array_equal(\n idx.get_indexer(idx), np.array([0, 1, 2], dtype=np.intp)\n )\n\n target = [-0.1, 0.5, 1.1]\n tm.assert_numpy_array_equal(\n idx.get_indexer(target, "pad"), np.array([-1, 0, 1], dtype=np.intp)\n )\n tm.assert_numpy_array_equal(\n idx.get_indexer(target, "backfill"), np.array([0, 1, 2], dtype=np.intp)\n )\n tm.assert_numpy_array_equal(\n idx.get_indexer(target, "nearest"), np.array([0, 1, 1], dtype=np.intp)\n )\n\n def test_get_indexer_nan(self):\n # GH#7820\n result = Index([1, 2, np.nan], dtype=np.float64).get_indexer([np.nan])\n expected = np.array([2], dtype=np.intp)\n tm.assert_numpy_array_equal(result, expected)\n\n def test_get_indexer_int64(self):\n index = Index(range(0, 20, 2), dtype=np.int64)\n target = Index(np.arange(10), dtype=np.int64)\n indexer = index.get_indexer(target)\n expected = np.array([0, -1, 1, -1, 2, -1, 3, -1, 4, -1], dtype=np.intp)\n tm.assert_numpy_array_equal(indexer, expected)\n\n target = Index(np.arange(10), dtype=np.int64)\n indexer = index.get_indexer(target, method="pad")\n expected = np.array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4], dtype=np.intp)\n tm.assert_numpy_array_equal(indexer, expected)\n\n target = Index(np.arange(10), dtype=np.int64)\n indexer = index.get_indexer(target, method="backfill")\n expected = np.array([0, 1, 1, 2, 2, 3, 3, 4, 4, 5], dtype=np.intp)\n tm.assert_numpy_array_equal(indexer, expected)\n\n def test_get_indexer_uint64(self, index_large):\n target = Index(np.arange(10).astype("uint64") * 5 + 2**63)\n indexer = index_large.get_indexer(target)\n expected = np.array([0, -1, 1, 2, 3, 4, -1, -1, -1, -1], dtype=np.intp)\n tm.assert_numpy_array_equal(indexer, expected)\n\n target = Index(np.arange(10).astype("uint64") * 5 + 2**63)\n indexer = index_large.get_indexer(target, method="pad")\n expected = np.array([0, 0, 1, 2, 3, 4, 4, 4, 4, 4], dtype=np.intp)\n tm.assert_numpy_array_equal(indexer, expected)\n\n target = Index(np.arange(10).astype("uint64") * 5 + 2**63)\n indexer = index_large.get_indexer(target, method="backfill")\n expected = np.array([0, 1, 1, 2, 3, 4, -1, -1, -1, -1], dtype=np.intp)\n tm.assert_numpy_array_equal(indexer, expected)\n\n @pytest.mark.parametrize("val, val2", [(4, 5), (4, 4), (4, NA), (NA, NA)])\n def test_get_loc_masked(self, val, val2, any_numeric_ea_and_arrow_dtype):\n # GH#39133\n idx = Index([1, 2, 3, val, val2], dtype=any_numeric_ea_and_arrow_dtype)\n result = idx.get_loc(2)\n assert result == 1\n\n with pytest.raises(KeyError, match="9"):\n idx.get_loc(9)\n\n def test_get_loc_masked_na(self, any_numeric_ea_and_arrow_dtype):\n # GH#39133\n idx = Index([1, 2, NA], dtype=any_numeric_ea_and_arrow_dtype)\n result = idx.get_loc(NA)\n assert result == 2\n\n idx = Index([1, 2, NA, NA], dtype=any_numeric_ea_and_arrow_dtype)\n result = idx.get_loc(NA)\n tm.assert_numpy_array_equal(result, np.array([False, False, True, True]))\n\n idx = Index([1, 2, 3], dtype=any_numeric_ea_and_arrow_dtype)\n with pytest.raises(KeyError, match="NA"):\n idx.get_loc(NA)\n\n def test_get_loc_masked_na_and_nan(self):\n # GH#39133\n idx = Index(\n FloatingArray(\n np.array([1, 2, 1, np.nan]), mask=np.array([False, False, True, False])\n )\n )\n result = idx.get_loc(NA)\n assert result == 2\n result = idx.get_loc(np.nan)\n assert result == 3\n\n idx = Index(\n FloatingArray(np.array([1, 2, 1.0]), mask=np.array([False, False, True]))\n )\n result = idx.get_loc(NA)\n assert result == 2\n with pytest.raises(KeyError, match="nan"):\n idx.get_loc(np.nan)\n\n idx = Index(\n FloatingArray(\n np.array([1, 2, np.nan]), mask=np.array([False, False, False])\n )\n )\n result = idx.get_loc(np.nan)\n assert result == 2\n with pytest.raises(KeyError, match="NA"):\n idx.get_loc(NA)\n\n @pytest.mark.parametrize("val", [4, 2])\n def test_get_indexer_masked_na(self, any_numeric_ea_and_arrow_dtype, val):\n # GH#39133\n idx = Index([1, 2, NA, 3, val], dtype=any_numeric_ea_and_arrow_dtype)\n result = idx.get_indexer_for([1, NA, 5])\n expected = np.array([0, 2, -1])\n tm.assert_numpy_array_equal(result, expected, check_dtype=False)\n\n @pytest.mark.parametrize("dtype", ["boolean", "bool[pyarrow]"])\n def test_get_indexer_masked_na_boolean(self, dtype):\n # GH#39133\n if dtype == "bool[pyarrow]":\n pytest.importorskip("pyarrow")\n idx = Index([True, False, NA], dtype=dtype)\n result = idx.get_loc(False)\n assert result == 1\n result = idx.get_loc(NA)\n assert result == 2\n\n def test_get_indexer_arrow_dictionary_target(self):\n pa = pytest.importorskip("pyarrow")\n target = Index(\n ArrowExtensionArray(\n pa.array([1, 2], type=pa.dictionary(pa.int8(), pa.int8()))\n )\n )\n idx = Index([1])\n\n result = idx.get_indexer(target)\n expected = np.array([0, -1], dtype=np.int64)\n tm.assert_numpy_array_equal(result, expected)\n\n result_1, result_2 = idx.get_indexer_non_unique(target)\n expected_1, expected_2 = np.array([0, -1], dtype=np.int64), np.array(\n [1], dtype=np.int64\n )\n tm.assert_numpy_array_equal(result_1, expected_1)\n tm.assert_numpy_array_equal(result_2, expected_2)\n\n\nclass TestWhere:\n @pytest.mark.parametrize(\n "index",\n [\n Index(np.arange(5, dtype="float64")),\n Index(range(0, 20, 2), dtype=np.int64),\n Index(np.arange(5, dtype="uint64")),\n ],\n )\n def test_where(self, listlike_box, index):\n cond = [True] * len(index)\n expected = index\n result = index.where(listlike_box(cond))\n\n cond = [False] + [True] * (len(index) - 1)\n expected = Index([index._na_value] + index[1:].tolist(), dtype=np.float64)\n result = index.where(listlike_box(cond))\n tm.assert_index_equal(result, expected)\n\n def test_where_uint64(self):\n idx = Index([0, 6, 2], dtype=np.uint64)\n mask = np.array([False, True, False])\n other = np.array([1], dtype=np.int64)\n\n expected = Index([1, 6, 1], dtype=np.uint64)\n\n result = idx.where(mask, other)\n tm.assert_index_equal(result, expected)\n\n result = idx.putmask(~mask, other)\n tm.assert_index_equal(result, expected)\n\n def test_where_infers_type_instead_of_trying_to_convert_string_to_float(self):\n # GH 32413\n index = Index([1, np.nan])\n cond = index.notna()\n other = Index(["a", "b"], dtype="string")\n\n expected = Index([1.0, "b"])\n result = index.where(cond, other)\n\n tm.assert_index_equal(result, expected)\n\n\nclass TestTake:\n @pytest.mark.parametrize("idx_dtype", [np.float64, np.int64, np.uint64])\n def test_take_preserve_name(self, idx_dtype):\n index = Index([1, 2, 3, 4], dtype=idx_dtype, name="foo")\n taken = index.take([3, 0, 1])\n assert index.name == taken.name\n\n def test_take_fill_value_float64(self):\n # GH 12631\n idx = Index([1.0, 2.0, 3.0], name="xxx", dtype=np.float64)\n result = idx.take(np.array([1, 0, -1]))\n expected = Index([2.0, 1.0, 3.0], dtype=np.float64, name="xxx")\n tm.assert_index_equal(result, expected)\n\n # fill_value\n result = idx.take(np.array([1, 0, -1]), fill_value=True)\n expected = Index([2.0, 1.0, np.nan], dtype=np.float64, name="xxx")\n tm.assert_index_equal(result, expected)\n\n # allow_fill=False\n result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True)\n expected = Index([2.0, 1.0, 3.0], dtype=np.float64, name="xxx")\n tm.assert_index_equal(result, expected)\n\n msg = (\n "When allow_fill=True and fill_value is not None, "\n "all indices must be >= -1"\n )\n with pytest.raises(ValueError, match=msg):\n idx.take(np.array([1, 0, -2]), fill_value=True)\n with pytest.raises(ValueError, match=msg):\n idx.take(np.array([1, 0, -5]), fill_value=True)\n\n msg = "index -5 is out of bounds for (axis 0 with )?size 3"\n with pytest.raises(IndexError, match=msg):\n idx.take(np.array([1, -5]))\n\n @pytest.mark.parametrize("dtype", [np.int64, np.uint64])\n def test_take_fill_value_ints(self, dtype):\n # see gh-12631\n idx = Index([1, 2, 3], dtype=dtype, name="xxx")\n result = idx.take(np.array([1, 0, -1]))\n expected = Index([2, 1, 3], dtype=dtype, name="xxx")\n tm.assert_index_equal(result, expected)\n\n name = type(idx).__name__\n msg = f"Unable to fill values because {name} cannot contain NA"\n\n # fill_value=True\n with pytest.raises(ValueError, match=msg):\n idx.take(np.array([1, 0, -1]), fill_value=True)\n\n # allow_fill=False\n result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True)\n expected = Index([2, 1, 3], dtype=dtype, name="xxx")\n tm.assert_index_equal(result, expected)\n\n with pytest.raises(ValueError, match=msg):\n idx.take(np.array([1, 0, -2]), fill_value=True)\n with pytest.raises(ValueError, match=msg):\n idx.take(np.array([1, 0, -5]), fill_value=True)\n\n msg = "index -5 is out of bounds for (axis 0 with )?size 3"\n with pytest.raises(IndexError, match=msg):\n idx.take(np.array([1, -5]))\n\n\nclass TestContains:\n @pytest.mark.parametrize("dtype", [np.float64, np.int64, np.uint64])\n def test_contains_none(self, dtype):\n # GH#35788 should return False, not raise TypeError\n index = Index([0, 1, 2, 3, 4], dtype=dtype)\n assert None not in index\n\n def test_contains_float64_nans(self):\n index = Index([1.0, 2.0, np.nan], dtype=np.float64)\n assert np.nan in index\n\n def test_contains_float64_not_nans(self):\n index = Index([1.0, 2.0, np.nan], dtype=np.float64)\n assert 1.0 in index\n\n\nclass TestSliceLocs:\n @pytest.mark.parametrize("dtype", [int, float])\n def test_slice_locs(self, dtype):\n index = Index(np.array([0, 1, 2, 5, 6, 7, 9, 10], dtype=dtype))\n n = len(index)\n\n assert index.slice_locs(start=2) == (2, n)\n assert index.slice_locs(start=3) == (3, n)\n assert index.slice_locs(3, 8) == (3, 6)\n assert index.slice_locs(5, 10) == (3, n)\n assert index.slice_locs(end=8) == (0, 6)\n assert index.slice_locs(end=9) == (0, 7)\n\n # reversed\n index2 = index[::-1]\n assert index2.slice_locs(8, 2) == (2, 6)\n assert index2.slice_locs(7, 3) == (2, 5)\n\n @pytest.mark.parametrize("dtype", [int, float])\n def test_slice_locs_float_locs(self, dtype):\n index = Index(np.array([0, 1, 2, 5, 6, 7, 9, 10], dtype=dtype))\n n = len(index)\n assert index.slice_locs(5.0, 10.0) == (3, n)\n assert index.slice_locs(4.5, 10.5) == (3, 8)\n\n index2 = index[::-1]\n assert index2.slice_locs(8.5, 1.5) == (2, 6)\n assert index2.slice_locs(10.5, -1) == (0, n)\n\n @pytest.mark.parametrize("dtype", [int, float])\n def test_slice_locs_dup_numeric(self, dtype):\n index = Index(np.array([10, 12, 12, 14], dtype=dtype))\n assert index.slice_locs(12, 12) == (1, 3)\n assert index.slice_locs(11, 13) == (1, 3)\n\n index2 = index[::-1]\n assert index2.slice_locs(12, 12) == (1, 3)\n assert index2.slice_locs(13, 11) == (1, 3)\n\n def test_slice_locs_na(self):\n index = Index([np.nan, 1, 2])\n assert index.slice_locs(1) == (1, 3)\n assert index.slice_locs(np.nan) == (0, 3)\n\n index = Index([0, np.nan, np.nan, 1, 2])\n assert index.slice_locs(np.nan) == (1, 5)\n\n def test_slice_locs_na_raises(self):\n index = Index([np.nan, 1, 2])\n with pytest.raises(KeyError, match=""):\n index.slice_locs(start=1.5)\n\n with pytest.raises(KeyError, match=""):\n index.slice_locs(end=1.5)\n\n\nclass TestGetSliceBounds:\n @pytest.mark.parametrize("side, expected", [("left", 4), ("right", 5)])\n def test_get_slice_bounds_within(self, side, expected):\n index = Index(range(6))\n result = index.get_slice_bound(4, side=side)\n assert result == expected\n\n @pytest.mark.parametrize("side", ["left", "right"])\n @pytest.mark.parametrize("bound, expected", [(-1, 0), (10, 6)])\n def test_get_slice_bounds_outside(self, side, expected, bound):\n index = Index(range(6))\n result = index.get_slice_bound(bound, side=side)\n assert result == expected\n | .venv\Lib\site-packages\pandas\tests\indexes\numeric\test_indexing.py | test_indexing.py | Python | 22,761 | 0.95 | 0.0982 | 0.0501 | node-utils | 894 | 2023-09-07T02:51:56.540270 | MIT | true | 92b446a6b31c54daeace55f8689ea365 |
import numpy as np\nimport pytest\n\nimport pandas._testing as tm\nfrom pandas.core.indexes.api import Index\n\n\nclass TestJoinInt64Index:\n def test_join_non_unique(self):\n left = Index([4, 4, 3, 3])\n\n joined, lidx, ridx = left.join(left, return_indexers=True)\n\n exp_joined = Index([4, 4, 4, 4, 3, 3, 3, 3])\n tm.assert_index_equal(joined, exp_joined)\n\n exp_lidx = np.array([0, 0, 1, 1, 2, 2, 3, 3], dtype=np.intp)\n tm.assert_numpy_array_equal(lidx, exp_lidx)\n\n exp_ridx = np.array([0, 1, 0, 1, 2, 3, 2, 3], dtype=np.intp)\n tm.assert_numpy_array_equal(ridx, exp_ridx)\n\n def test_join_inner(self):\n index = Index(range(0, 20, 2), dtype=np.int64)\n other = Index([7, 12, 25, 1, 2, 5], dtype=np.int64)\n other_mono = Index([1, 2, 5, 7, 12, 25], dtype=np.int64)\n\n # not monotonic\n res, lidx, ridx = index.join(other, how="inner", return_indexers=True)\n\n # no guarantee of sortedness, so sort for comparison purposes\n ind = res.argsort()\n res = res.take(ind)\n lidx = lidx.take(ind)\n ridx = ridx.take(ind)\n\n eres = Index([2, 12], dtype=np.int64)\n elidx = np.array([1, 6], dtype=np.intp)\n eridx = np.array([4, 1], dtype=np.intp)\n\n assert isinstance(res, Index) and res.dtype == np.int64\n tm.assert_index_equal(res, eres)\n tm.assert_numpy_array_equal(lidx, elidx)\n tm.assert_numpy_array_equal(ridx, eridx)\n\n # monotonic\n res, lidx, ridx = index.join(other_mono, how="inner", return_indexers=True)\n\n res2 = index.intersection(other_mono)\n tm.assert_index_equal(res, res2)\n\n elidx = np.array([1, 6], dtype=np.intp)\n eridx = np.array([1, 4], dtype=np.intp)\n assert isinstance(res, Index) and res.dtype == np.int64\n tm.assert_index_equal(res, eres)\n tm.assert_numpy_array_equal(lidx, elidx)\n tm.assert_numpy_array_equal(ridx, eridx)\n\n def test_join_left(self):\n index = Index(range(0, 20, 2), dtype=np.int64)\n other = Index([7, 12, 25, 1, 2, 5], dtype=np.int64)\n other_mono = Index([1, 2, 5, 7, 12, 25], dtype=np.int64)\n\n # not monotonic\n res, lidx, ridx = index.join(other, how="left", return_indexers=True)\n eres = index\n eridx = np.array([-1, 4, -1, -1, -1, -1, 1, -1, -1, -1], dtype=np.intp)\n\n assert isinstance(res, Index) and res.dtype == np.int64\n tm.assert_index_equal(res, eres)\n assert lidx is None\n tm.assert_numpy_array_equal(ridx, eridx)\n\n # monotonic\n res, lidx, ridx = index.join(other_mono, how="left", return_indexers=True)\n eridx = np.array([-1, 1, -1, -1, -1, -1, 4, -1, -1, -1], dtype=np.intp)\n assert isinstance(res, Index) and res.dtype == np.int64\n tm.assert_index_equal(res, eres)\n assert lidx is None\n tm.assert_numpy_array_equal(ridx, eridx)\n\n # non-unique\n idx = Index([1, 1, 2, 5])\n idx2 = Index([1, 2, 5, 7, 9])\n res, lidx, ridx = idx2.join(idx, how="left", return_indexers=True)\n eres = Index([1, 1, 2, 5, 7, 9]) # 1 is in idx2, so it should be x2\n eridx = np.array([0, 1, 2, 3, -1, -1], dtype=np.intp)\n elidx = np.array([0, 0, 1, 2, 3, 4], dtype=np.intp)\n tm.assert_index_equal(res, eres)\n tm.assert_numpy_array_equal(lidx, elidx)\n tm.assert_numpy_array_equal(ridx, eridx)\n\n def test_join_right(self):\n index = Index(range(0, 20, 2), dtype=np.int64)\n other = Index([7, 12, 25, 1, 2, 5], dtype=np.int64)\n other_mono = Index([1, 2, 5, 7, 12, 25], dtype=np.int64)\n\n # not monotonic\n res, lidx, ridx = index.join(other, how="right", return_indexers=True)\n eres = other\n elidx = np.array([-1, 6, -1, -1, 1, -1], dtype=np.intp)\n\n assert isinstance(other, Index) and other.dtype == np.int64\n tm.assert_index_equal(res, eres)\n tm.assert_numpy_array_equal(lidx, elidx)\n assert ridx is None\n\n # monotonic\n res, lidx, ridx = index.join(other_mono, how="right", return_indexers=True)\n eres = other_mono\n elidx = np.array([-1, 1, -1, -1, 6, -1], dtype=np.intp)\n assert isinstance(other, Index) and other.dtype == np.int64\n tm.assert_index_equal(res, eres)\n tm.assert_numpy_array_equal(lidx, elidx)\n assert ridx is None\n\n # non-unique\n idx = Index([1, 1, 2, 5])\n idx2 = Index([1, 2, 5, 7, 9])\n res, lidx, ridx = idx.join(idx2, how="right", return_indexers=True)\n eres = Index([1, 1, 2, 5, 7, 9]) # 1 is in idx2, so it should be x2\n elidx = np.array([0, 1, 2, 3, -1, -1], dtype=np.intp)\n eridx = np.array([0, 0, 1, 2, 3, 4], dtype=np.intp)\n tm.assert_index_equal(res, eres)\n tm.assert_numpy_array_equal(lidx, elidx)\n tm.assert_numpy_array_equal(ridx, eridx)\n\n def test_join_non_int_index(self):\n index = Index(range(0, 20, 2), dtype=np.int64)\n other = Index([3, 6, 7, 8, 10], dtype=object)\n\n outer = index.join(other, how="outer")\n outer2 = other.join(index, how="outer")\n expected = Index([0, 2, 3, 4, 6, 7, 8, 10, 12, 14, 16, 18])\n tm.assert_index_equal(outer, outer2)\n tm.assert_index_equal(outer, expected)\n\n inner = index.join(other, how="inner")\n inner2 = other.join(index, how="inner")\n expected = Index([6, 8, 10])\n tm.assert_index_equal(inner, inner2)\n tm.assert_index_equal(inner, expected)\n\n left = index.join(other, how="left")\n tm.assert_index_equal(left, index.astype(object))\n\n left2 = other.join(index, how="left")\n tm.assert_index_equal(left2, other)\n\n right = index.join(other, how="right")\n tm.assert_index_equal(right, other)\n\n right2 = other.join(index, how="right")\n tm.assert_index_equal(right2, index.astype(object))\n\n def test_join_outer(self):\n index = Index(range(0, 20, 2), dtype=np.int64)\n other = Index([7, 12, 25, 1, 2, 5], dtype=np.int64)\n other_mono = Index([1, 2, 5, 7, 12, 25], dtype=np.int64)\n\n # not monotonic\n # guarantee of sortedness\n res, lidx, ridx = index.join(other, how="outer", return_indexers=True)\n noidx_res = index.join(other, how="outer")\n tm.assert_index_equal(res, noidx_res)\n\n eres = Index([0, 1, 2, 4, 5, 6, 7, 8, 10, 12, 14, 16, 18, 25], dtype=np.int64)\n elidx = np.array([0, -1, 1, 2, -1, 3, -1, 4, 5, 6, 7, 8, 9, -1], dtype=np.intp)\n eridx = np.array(\n [-1, 3, 4, -1, 5, -1, 0, -1, -1, 1, -1, -1, -1, 2], dtype=np.intp\n )\n\n assert isinstance(res, Index) and res.dtype == np.int64\n tm.assert_index_equal(res, eres)\n tm.assert_numpy_array_equal(lidx, elidx)\n tm.assert_numpy_array_equal(ridx, eridx)\n\n # monotonic\n res, lidx, ridx = index.join(other_mono, how="outer", return_indexers=True)\n noidx_res = index.join(other_mono, how="outer")\n tm.assert_index_equal(res, noidx_res)\n\n elidx = np.array([0, -1, 1, 2, -1, 3, -1, 4, 5, 6, 7, 8, 9, -1], dtype=np.intp)\n eridx = np.array(\n [-1, 0, 1, -1, 2, -1, 3, -1, -1, 4, -1, -1, -1, 5], dtype=np.intp\n )\n assert isinstance(res, Index) and res.dtype == np.int64\n tm.assert_index_equal(res, eres)\n tm.assert_numpy_array_equal(lidx, elidx)\n tm.assert_numpy_array_equal(ridx, eridx)\n\n\nclass TestJoinUInt64Index:\n @pytest.fixture\n def index_large(self):\n # large values used in TestUInt64Index where no compat needed with int64/float64\n large = [2**63, 2**63 + 10, 2**63 + 15, 2**63 + 20, 2**63 + 25]\n return Index(large, dtype=np.uint64)\n\n def test_join_inner(self, index_large):\n other = Index(2**63 + np.array([7, 12, 25, 1, 2, 10], dtype="uint64"))\n other_mono = Index(2**63 + np.array([1, 2, 7, 10, 12, 25], dtype="uint64"))\n\n # not monotonic\n res, lidx, ridx = index_large.join(other, how="inner", return_indexers=True)\n\n # no guarantee of sortedness, so sort for comparison purposes\n ind = res.argsort()\n res = res.take(ind)\n lidx = lidx.take(ind)\n ridx = ridx.take(ind)\n\n eres = Index(2**63 + np.array([10, 25], dtype="uint64"))\n elidx = np.array([1, 4], dtype=np.intp)\n eridx = np.array([5, 2], dtype=np.intp)\n\n assert isinstance(res, Index) and res.dtype == np.uint64\n tm.assert_index_equal(res, eres)\n tm.assert_numpy_array_equal(lidx, elidx)\n tm.assert_numpy_array_equal(ridx, eridx)\n\n # monotonic\n res, lidx, ridx = index_large.join(\n other_mono, how="inner", return_indexers=True\n )\n\n res2 = index_large.intersection(other_mono)\n tm.assert_index_equal(res, res2)\n\n elidx = np.array([1, 4], dtype=np.intp)\n eridx = np.array([3, 5], dtype=np.intp)\n\n assert isinstance(res, Index) and res.dtype == np.uint64\n tm.assert_index_equal(res, eres)\n tm.assert_numpy_array_equal(lidx, elidx)\n tm.assert_numpy_array_equal(ridx, eridx)\n\n def test_join_left(self, index_large):\n other = Index(2**63 + np.array([7, 12, 25, 1, 2, 10], dtype="uint64"))\n other_mono = Index(2**63 + np.array([1, 2, 7, 10, 12, 25], dtype="uint64"))\n\n # not monotonic\n res, lidx, ridx = index_large.join(other, how="left", return_indexers=True)\n eres = index_large\n eridx = np.array([-1, 5, -1, -1, 2], dtype=np.intp)\n\n assert isinstance(res, Index) and res.dtype == np.uint64\n tm.assert_index_equal(res, eres)\n assert lidx is None\n tm.assert_numpy_array_equal(ridx, eridx)\n\n # monotonic\n res, lidx, ridx = index_large.join(other_mono, how="left", return_indexers=True)\n eridx = np.array([-1, 3, -1, -1, 5], dtype=np.intp)\n\n assert isinstance(res, Index) and res.dtype == np.uint64\n tm.assert_index_equal(res, eres)\n assert lidx is None\n tm.assert_numpy_array_equal(ridx, eridx)\n\n # non-unique\n idx = Index(2**63 + np.array([1, 1, 2, 5], dtype="uint64"))\n idx2 = Index(2**63 + np.array([1, 2, 5, 7, 9], dtype="uint64"))\n res, lidx, ridx = idx2.join(idx, how="left", return_indexers=True)\n\n # 1 is in idx2, so it should be x2\n eres = Index(2**63 + np.array([1, 1, 2, 5, 7, 9], dtype="uint64"))\n eridx = np.array([0, 1, 2, 3, -1, -1], dtype=np.intp)\n elidx = np.array([0, 0, 1, 2, 3, 4], dtype=np.intp)\n\n tm.assert_index_equal(res, eres)\n tm.assert_numpy_array_equal(lidx, elidx)\n tm.assert_numpy_array_equal(ridx, eridx)\n\n def test_join_right(self, index_large):\n other = Index(2**63 + np.array([7, 12, 25, 1, 2, 10], dtype="uint64"))\n other_mono = Index(2**63 + np.array([1, 2, 7, 10, 12, 25], dtype="uint64"))\n\n # not monotonic\n res, lidx, ridx = index_large.join(other, how="right", return_indexers=True)\n eres = other\n elidx = np.array([-1, -1, 4, -1, -1, 1], dtype=np.intp)\n\n tm.assert_numpy_array_equal(lidx, elidx)\n assert isinstance(other, Index) and other.dtype == np.uint64\n tm.assert_index_equal(res, eres)\n assert ridx is None\n\n # monotonic\n res, lidx, ridx = index_large.join(\n other_mono, how="right", return_indexers=True\n )\n eres = other_mono\n elidx = np.array([-1, -1, -1, 1, -1, 4], dtype=np.intp)\n\n assert isinstance(other, Index) and other.dtype == np.uint64\n tm.assert_numpy_array_equal(lidx, elidx)\n tm.assert_index_equal(res, eres)\n assert ridx is None\n\n # non-unique\n idx = Index(2**63 + np.array([1, 1, 2, 5], dtype="uint64"))\n idx2 = Index(2**63 + np.array([1, 2, 5, 7, 9], dtype="uint64"))\n res, lidx, ridx = idx.join(idx2, how="right", return_indexers=True)\n\n # 1 is in idx2, so it should be x2\n eres = Index(2**63 + np.array([1, 1, 2, 5, 7, 9], dtype="uint64"))\n elidx = np.array([0, 1, 2, 3, -1, -1], dtype=np.intp)\n eridx = np.array([0, 0, 1, 2, 3, 4], dtype=np.intp)\n\n tm.assert_index_equal(res, eres)\n tm.assert_numpy_array_equal(lidx, elidx)\n tm.assert_numpy_array_equal(ridx, eridx)\n\n def test_join_non_int_index(self, index_large):\n other = Index(\n 2**63 + np.array([1, 5, 7, 10, 20], dtype="uint64"), dtype=object\n )\n\n outer = index_large.join(other, how="outer")\n outer2 = other.join(index_large, how="outer")\n expected = Index(\n 2**63 + np.array([0, 1, 5, 7, 10, 15, 20, 25], dtype="uint64")\n )\n tm.assert_index_equal(outer, outer2)\n tm.assert_index_equal(outer, expected)\n\n inner = index_large.join(other, how="inner")\n inner2 = other.join(index_large, how="inner")\n expected = Index(2**63 + np.array([10, 20], dtype="uint64"))\n tm.assert_index_equal(inner, inner2)\n tm.assert_index_equal(inner, expected)\n\n left = index_large.join(other, how="left")\n tm.assert_index_equal(left, index_large.astype(object))\n\n left2 = other.join(index_large, how="left")\n tm.assert_index_equal(left2, other)\n\n right = index_large.join(other, how="right")\n tm.assert_index_equal(right, other)\n\n right2 = other.join(index_large, how="right")\n tm.assert_index_equal(right2, index_large.astype(object))\n\n def test_join_outer(self, index_large):\n other = Index(2**63 + np.array([7, 12, 25, 1, 2, 10], dtype="uint64"))\n other_mono = Index(2**63 + np.array([1, 2, 7, 10, 12, 25], dtype="uint64"))\n\n # not monotonic\n # guarantee of sortedness\n res, lidx, ridx = index_large.join(other, how="outer", return_indexers=True)\n noidx_res = index_large.join(other, how="outer")\n tm.assert_index_equal(res, noidx_res)\n\n eres = Index(\n 2**63 + np.array([0, 1, 2, 7, 10, 12, 15, 20, 25], dtype="uint64")\n )\n elidx = np.array([0, -1, -1, -1, 1, -1, 2, 3, 4], dtype=np.intp)\n eridx = np.array([-1, 3, 4, 0, 5, 1, -1, -1, 2], dtype=np.intp)\n\n assert isinstance(res, Index) and res.dtype == np.uint64\n tm.assert_index_equal(res, eres)\n tm.assert_numpy_array_equal(lidx, elidx)\n tm.assert_numpy_array_equal(ridx, eridx)\n\n # monotonic\n res, lidx, ridx = index_large.join(\n other_mono, how="outer", return_indexers=True\n )\n noidx_res = index_large.join(other_mono, how="outer")\n tm.assert_index_equal(res, noidx_res)\n\n elidx = np.array([0, -1, -1, -1, 1, -1, 2, 3, 4], dtype=np.intp)\n eridx = np.array([-1, 0, 1, 2, 3, 4, -1, -1, 5], dtype=np.intp)\n\n assert isinstance(res, Index) and res.dtype == np.uint64\n tm.assert_index_equal(res, eres)\n tm.assert_numpy_array_equal(lidx, elidx)\n tm.assert_numpy_array_equal(ridx, eridx)\n | .venv\Lib\site-packages\pandas\tests\indexes\numeric\test_join.py | test_join.py | Python | 15,039 | 0.95 | 0.042105 | 0.089701 | vue-tools | 945 | 2024-05-27T00:17:15.169567 | Apache-2.0 | true | 35254dbde42aa59081aedd905d90e247 |
import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n Index,\n Series,\n)\nimport pandas._testing as tm\n\n\nclass TestFloatNumericIndex:\n @pytest.fixture(params=[np.float64, np.float32])\n def dtype(self, request):\n return request.param\n\n @pytest.fixture\n def simple_index(self, dtype):\n values = np.arange(5, dtype=dtype)\n return Index(values)\n\n @pytest.fixture(\n params=[\n [1.5, 2, 3, 4, 5],\n [0.0, 2.5, 5.0, 7.5, 10.0],\n [5, 4, 3, 2, 1.5],\n [10.0, 7.5, 5.0, 2.5, 0.0],\n ],\n ids=["mixed", "float", "mixed_dec", "float_dec"],\n )\n def index(self, request, dtype):\n return Index(request.param, dtype=dtype)\n\n @pytest.fixture\n def mixed_index(self, dtype):\n return Index([1.5, 2, 3, 4, 5], dtype=dtype)\n\n @pytest.fixture\n def float_index(self, dtype):\n return Index([0.0, 2.5, 5.0, 7.5, 10.0], dtype=dtype)\n\n def test_repr_roundtrip(self, index):\n tm.assert_index_equal(eval(repr(index)), index, exact=True)\n\n def check_coerce(self, a, b, is_float_index=True):\n assert a.equals(b)\n tm.assert_index_equal(a, b, exact=False)\n if is_float_index:\n assert isinstance(b, Index)\n else:\n assert type(b) is Index\n\n def test_constructor_from_list_no_dtype(self):\n index = Index([1.5, 2.5, 3.5])\n assert index.dtype == np.float64\n\n def test_constructor(self, dtype):\n index_cls = Index\n\n # explicit construction\n index = index_cls([1, 2, 3, 4, 5], dtype=dtype)\n\n assert isinstance(index, index_cls)\n assert index.dtype == dtype\n\n expected = np.array([1, 2, 3, 4, 5], dtype=dtype)\n tm.assert_numpy_array_equal(index.values, expected)\n\n index = index_cls(np.array([1, 2, 3, 4, 5]), dtype=dtype)\n assert isinstance(index, index_cls)\n assert index.dtype == dtype\n\n index = index_cls([1.0, 2, 3, 4, 5], dtype=dtype)\n assert isinstance(index, index_cls)\n assert index.dtype == dtype\n\n index = index_cls(np.array([1.0, 2, 3, 4, 5]), dtype=dtype)\n assert isinstance(index, index_cls)\n assert index.dtype == dtype\n\n index = index_cls([1.0, 2, 3, 4, 5], dtype=dtype)\n assert isinstance(index, index_cls)\n assert index.dtype == dtype\n\n index = index_cls(np.array([1.0, 2, 3, 4, 5]), dtype=dtype)\n assert isinstance(index, index_cls)\n assert index.dtype == dtype\n\n # nan handling\n result = index_cls([np.nan, np.nan], dtype=dtype)\n assert pd.isna(result.values).all()\n\n result = index_cls(np.array([np.nan]), dtype=dtype)\n assert pd.isna(result.values).all()\n\n def test_constructor_invalid(self):\n index_cls = Index\n cls_name = index_cls.__name__\n # invalid\n msg = (\n rf"{cls_name}\(\.\.\.\) must be called with a collection of "\n r"some kind, 0\.0 was passed"\n )\n with pytest.raises(TypeError, match=msg):\n index_cls(0.0)\n\n def test_constructor_coerce(self, mixed_index, float_index):\n self.check_coerce(mixed_index, Index([1.5, 2, 3, 4, 5]))\n self.check_coerce(float_index, Index(np.arange(5) * 2.5))\n\n result = Index(np.array(np.arange(5) * 2.5, dtype=object))\n assert result.dtype == object # as of 2.0 to match Series\n self.check_coerce(float_index, result.astype("float64"))\n\n def test_constructor_explicit(self, mixed_index, float_index):\n # these don't auto convert\n self.check_coerce(\n float_index, Index((np.arange(5) * 2.5), dtype=object), is_float_index=False\n )\n self.check_coerce(\n mixed_index, Index([1.5, 2, 3, 4, 5], dtype=object), is_float_index=False\n )\n\n def test_type_coercion_fail(self, any_int_numpy_dtype):\n # see gh-15832\n msg = "Trying to coerce float values to integers"\n with pytest.raises(ValueError, match=msg):\n Index([1, 2, 3.5], dtype=any_int_numpy_dtype)\n\n def test_equals_numeric(self):\n index_cls = Index\n\n idx = index_cls([1.0, 2.0])\n assert idx.equals(idx)\n assert idx.identical(idx)\n\n idx2 = index_cls([1.0, 2.0])\n assert idx.equals(idx2)\n\n idx = index_cls([1.0, np.nan])\n assert idx.equals(idx)\n assert idx.identical(idx)\n\n idx2 = index_cls([1.0, np.nan])\n assert idx.equals(idx2)\n\n @pytest.mark.parametrize(\n "other",\n (\n Index([1, 2], dtype=np.int64),\n Index([1.0, 2.0], dtype=object),\n Index([1, 2], dtype=object),\n ),\n )\n def test_equals_numeric_other_index_type(self, other):\n idx = Index([1.0, 2.0])\n assert idx.equals(other)\n assert other.equals(idx)\n\n @pytest.mark.parametrize(\n "vals",\n [\n pd.date_range("2016-01-01", periods=3),\n pd.timedelta_range("1 Day", periods=3),\n ],\n )\n def test_lookups_datetimelike_values(self, vals, dtype):\n # If we have datetime64 or timedelta64 values, make sure they are\n # wrapped correctly GH#31163\n ser = Series(vals, index=range(3, 6))\n ser.index = ser.index.astype(dtype)\n\n expected = vals[1]\n\n result = ser[4.0]\n assert isinstance(result, type(expected)) and result == expected\n result = ser[4]\n assert isinstance(result, type(expected)) and result == expected\n\n result = ser.loc[4.0]\n assert isinstance(result, type(expected)) and result == expected\n result = ser.loc[4]\n assert isinstance(result, type(expected)) and result == expected\n\n result = ser.at[4.0]\n assert isinstance(result, type(expected)) and result == expected\n # GH#31329 .at[4] should cast to 4.0, matching .loc behavior\n result = ser.at[4]\n assert isinstance(result, type(expected)) and result == expected\n\n result = ser.iloc[1]\n assert isinstance(result, type(expected)) and result == expected\n\n result = ser.iat[1]\n assert isinstance(result, type(expected)) and result == expected\n\n def test_doesnt_contain_all_the_things(self):\n idx = Index([np.nan])\n assert not idx.isin([0]).item()\n assert not idx.isin([1]).item()\n assert idx.isin([np.nan]).item()\n\n def test_nan_multiple_containment(self):\n index_cls = Index\n\n idx = index_cls([1.0, np.nan])\n tm.assert_numpy_array_equal(idx.isin([1.0]), np.array([True, False]))\n tm.assert_numpy_array_equal(idx.isin([2.0, np.pi]), np.array([False, False]))\n tm.assert_numpy_array_equal(idx.isin([np.nan]), np.array([False, True]))\n tm.assert_numpy_array_equal(idx.isin([1.0, np.nan]), np.array([True, True]))\n idx = index_cls([1.0, 2.0])\n tm.assert_numpy_array_equal(idx.isin([np.nan]), np.array([False, False]))\n\n def test_fillna_float64(self):\n index_cls = Index\n # GH 11343\n idx = Index([1.0, np.nan, 3.0], dtype=float, name="x")\n # can't downcast\n exp = Index([1.0, 0.1, 3.0], name="x")\n tm.assert_index_equal(idx.fillna(0.1), exp, exact=True)\n\n # downcast\n exp = index_cls([1.0, 2.0, 3.0], name="x")\n tm.assert_index_equal(idx.fillna(2), exp)\n\n # object\n exp = Index([1.0, "obj", 3.0], name="x")\n tm.assert_index_equal(idx.fillna("obj"), exp, exact=True)\n\n def test_logical_compat(self, simple_index):\n idx = simple_index\n assert idx.all() == idx.values.all()\n assert idx.any() == idx.values.any()\n\n assert idx.all() == idx.to_series().all()\n assert idx.any() == idx.to_series().any()\n\n\nclass TestNumericInt:\n @pytest.fixture(params=[np.int64, np.int32, np.int16, np.int8, np.uint64])\n def dtype(self, request):\n return request.param\n\n @pytest.fixture\n def simple_index(self, dtype):\n return Index(range(0, 20, 2), dtype=dtype)\n\n def test_is_monotonic(self):\n index_cls = Index\n\n index = index_cls([1, 2, 3, 4])\n assert index.is_monotonic_increasing is True\n assert index.is_monotonic_increasing is True\n assert index._is_strictly_monotonic_increasing is True\n assert index.is_monotonic_decreasing is False\n assert index._is_strictly_monotonic_decreasing is False\n\n index = index_cls([4, 3, 2, 1])\n assert index.is_monotonic_increasing is False\n assert index._is_strictly_monotonic_increasing is False\n assert index._is_strictly_monotonic_decreasing is True\n\n index = index_cls([1])\n assert index.is_monotonic_increasing is True\n assert index.is_monotonic_increasing is True\n assert index.is_monotonic_decreasing is True\n assert index._is_strictly_monotonic_increasing is True\n assert index._is_strictly_monotonic_decreasing is True\n\n def test_is_strictly_monotonic(self):\n index_cls = Index\n\n index = index_cls([1, 1, 2, 3])\n assert index.is_monotonic_increasing is True\n assert index._is_strictly_monotonic_increasing is False\n\n index = index_cls([3, 2, 1, 1])\n assert index.is_monotonic_decreasing is True\n assert index._is_strictly_monotonic_decreasing is False\n\n index = index_cls([1, 1])\n assert index.is_monotonic_increasing\n assert index.is_monotonic_decreasing\n assert not index._is_strictly_monotonic_increasing\n assert not index._is_strictly_monotonic_decreasing\n\n def test_logical_compat(self, simple_index):\n idx = simple_index\n assert idx.all() == idx.values.all()\n assert idx.any() == idx.values.any()\n\n def test_identical(self, simple_index, dtype):\n index = simple_index\n\n idx = Index(index.copy())\n assert idx.identical(index)\n\n same_values_different_type = Index(idx, dtype=object)\n assert not idx.identical(same_values_different_type)\n\n idx = index.astype(dtype=object)\n idx = idx.rename("foo")\n same_values = Index(idx, dtype=object)\n assert same_values.identical(idx)\n\n assert not idx.identical(index)\n assert Index(same_values, name="foo", dtype=object).identical(idx)\n\n assert not index.astype(dtype=object).identical(index.astype(dtype=dtype))\n\n def test_cant_or_shouldnt_cast(self, dtype):\n msg = r"invalid literal for int\(\) with base 10: 'foo'"\n\n # can't\n data = ["foo", "bar", "baz"]\n with pytest.raises(ValueError, match=msg):\n Index(data, dtype=dtype)\n\n def test_view_index(self, simple_index):\n index = simple_index\n msg = "Passing a type in .*Index.view is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n index.view(Index)\n\n def test_prevent_casting(self, simple_index):\n index = simple_index\n result = index.astype("O")\n assert result.dtype == np.object_\n\n\nclass TestIntNumericIndex:\n @pytest.fixture(params=[np.int64, np.int32, np.int16, np.int8])\n def dtype(self, request):\n return request.param\n\n def test_constructor_from_list_no_dtype(self):\n index = Index([1, 2, 3])\n assert index.dtype == np.int64\n\n def test_constructor(self, dtype):\n index_cls = Index\n\n # scalar raise Exception\n msg = (\n rf"{index_cls.__name__}\(\.\.\.\) must be called with a collection of some "\n "kind, 5 was passed"\n )\n with pytest.raises(TypeError, match=msg):\n index_cls(5)\n\n # copy\n # pass list, coerce fine\n index = index_cls([-5, 0, 1, 2], dtype=dtype)\n arr = index.values.copy()\n new_index = index_cls(arr, copy=True)\n tm.assert_index_equal(new_index, index, exact=True)\n val = int(arr[0]) + 3000\n\n # this should not change index\n if dtype != np.int8:\n # NEP 50 won't allow assignment that would overflow\n arr[0] = val\n assert new_index[0] != val\n\n if dtype == np.int64:\n # pass list, coerce fine\n index = index_cls([-5, 0, 1, 2], dtype=dtype)\n expected = Index([-5, 0, 1, 2], dtype=dtype)\n tm.assert_index_equal(index, expected)\n\n # from iterable\n index = index_cls(iter([-5, 0, 1, 2]), dtype=dtype)\n expected = index_cls([-5, 0, 1, 2], dtype=dtype)\n tm.assert_index_equal(index, expected, exact=True)\n\n # interpret list-like\n expected = index_cls([5, 0], dtype=dtype)\n for cls in [Index, index_cls]:\n for idx in [\n cls([5, 0], dtype=dtype),\n cls(np.array([5, 0]), dtype=dtype),\n cls(Series([5, 0]), dtype=dtype),\n ]:\n tm.assert_index_equal(idx, expected)\n\n def test_constructor_corner(self, dtype):\n index_cls = Index\n\n arr = np.array([1, 2, 3, 4], dtype=object)\n\n index = index_cls(arr, dtype=dtype)\n assert index.values.dtype == index.dtype\n if dtype == np.int64:\n without_dtype = Index(arr)\n # as of 2.0 we do not infer a dtype when we get an object-dtype\n # ndarray of numbers, matching Series behavior\n assert without_dtype.dtype == object\n\n tm.assert_index_equal(index, without_dtype.astype(np.int64))\n\n # preventing casting\n arr = np.array([1, "2", 3, "4"], dtype=object)\n msg = "Trying to coerce float values to integers"\n with pytest.raises(ValueError, match=msg):\n index_cls(arr, dtype=dtype)\n\n def test_constructor_coercion_signed_to_unsigned(\n self,\n any_unsigned_int_numpy_dtype,\n ):\n # see gh-15832\n msg = "|".join(\n [\n "Trying to coerce negative values to unsigned integers",\n "The elements provided in the data cannot all be casted",\n ]\n )\n with pytest.raises(OverflowError, match=msg):\n Index([-1], dtype=any_unsigned_int_numpy_dtype)\n\n def test_constructor_np_signed(self, any_signed_int_numpy_dtype):\n # GH#47475\n scalar = np.dtype(any_signed_int_numpy_dtype).type(1)\n result = Index([scalar])\n expected = Index([1], dtype=any_signed_int_numpy_dtype)\n tm.assert_index_equal(result, expected, exact=True)\n\n def test_constructor_np_unsigned(self, any_unsigned_int_numpy_dtype):\n # GH#47475\n scalar = np.dtype(any_unsigned_int_numpy_dtype).type(1)\n result = Index([scalar])\n expected = Index([1], dtype=any_unsigned_int_numpy_dtype)\n tm.assert_index_equal(result, expected, exact=True)\n\n def test_coerce_list(self):\n # coerce things\n arr = Index([1, 2, 3, 4])\n assert isinstance(arr, Index)\n\n # but not if explicit dtype passed\n arr = Index([1, 2, 3, 4], dtype=object)\n assert type(arr) is Index\n\n\nclass TestFloat16Index:\n # float 16 indexes not supported\n # GH 49535\n def test_constructor(self):\n index_cls = Index\n dtype = np.float16\n\n msg = "float16 indexes are not supported"\n\n # explicit construction\n with pytest.raises(NotImplementedError, match=msg):\n index_cls([1, 2, 3, 4, 5], dtype=dtype)\n\n with pytest.raises(NotImplementedError, match=msg):\n index_cls(np.array([1, 2, 3, 4, 5]), dtype=dtype)\n\n with pytest.raises(NotImplementedError, match=msg):\n index_cls([1.0, 2, 3, 4, 5], dtype=dtype)\n\n with pytest.raises(NotImplementedError, match=msg):\n index_cls(np.array([1.0, 2, 3, 4, 5]), dtype=dtype)\n\n with pytest.raises(NotImplementedError, match=msg):\n index_cls([1.0, 2, 3, 4, 5], dtype=dtype)\n\n with pytest.raises(NotImplementedError, match=msg):\n index_cls(np.array([1.0, 2, 3, 4, 5]), dtype=dtype)\n\n # nan handling\n with pytest.raises(NotImplementedError, match=msg):\n index_cls([np.nan, np.nan], dtype=dtype)\n\n with pytest.raises(NotImplementedError, match=msg):\n index_cls(np.array([np.nan]), dtype=dtype)\n\n\n@pytest.mark.parametrize(\n "box",\n [list, lambda x: np.array(x, dtype=object), lambda x: Index(x, dtype=object)],\n)\ndef test_uint_index_does_not_convert_to_float64(box):\n # https://github.com/pandas-dev/pandas/issues/28279\n # https://github.com/pandas-dev/pandas/issues/28023\n series = Series(\n [0, 1, 2, 3, 4, 5],\n index=[\n 7606741985629028552,\n 17876870360202815256,\n 17876870360202815256,\n 13106359306506049338,\n 8991270399732411471,\n 8991270399732411472,\n ],\n )\n\n result = series.loc[box([7606741985629028552, 17876870360202815256])]\n\n expected = Index(\n [7606741985629028552, 17876870360202815256, 17876870360202815256],\n dtype="uint64",\n )\n tm.assert_index_equal(result.index, expected)\n\n tm.assert_equal(result, series.iloc[:3])\n\n\ndef test_float64_index_equals():\n # https://github.com/pandas-dev/pandas/issues/35217\n float_index = Index([1.0, 2, 3])\n string_index = Index(["1", "2", "3"])\n\n result = float_index.equals(string_index)\n assert result is False\n\n result = string_index.equals(float_index)\n assert result is False\n\n\ndef test_map_dtype_inference_unsigned_to_signed():\n # GH#44609 cases where we don't retain dtype\n idx = Index([1, 2, 3], dtype=np.uint64)\n result = idx.map(lambda x: -x)\n expected = Index([-1, -2, -3], dtype=np.int64)\n tm.assert_index_equal(result, expected)\n\n\ndef test_map_dtype_inference_overflows():\n # GH#44609 case where we have to upcast\n idx = Index(np.array([1, 2, 3], dtype=np.int8))\n result = idx.map(lambda x: x * 1000)\n # TODO: we could plausibly try to infer down to int16 here\n expected = Index([1000, 2000, 3000], dtype=np.int64)\n tm.assert_index_equal(result, expected)\n\n\ndef test_view_to_datetimelike():\n # GH#55710\n idx = Index([1, 2, 3])\n res = idx.view("m8[s]")\n expected = pd.TimedeltaIndex(idx.values.view("m8[s]"))\n tm.assert_index_equal(res, expected)\n\n res2 = idx.view("m8[D]")\n expected2 = idx.values.view("m8[D]")\n tm.assert_numpy_array_equal(res2, expected2)\n\n res3 = idx.view("M8[h]")\n expected3 = idx.values.view("M8[h]")\n tm.assert_numpy_array_equal(res3, expected3)\n | .venv\Lib\site-packages\pandas\tests\indexes\numeric\test_numeric.py | test_numeric.py | Python | 18,586 | 0.95 | 0.101266 | 0.091743 | python-kit | 487 | 2025-07-01T16:21:55.437093 | GPL-3.0 | true | 187c10eb332c6163f5f4499e40f7393e |
from datetime import (\n datetime,\n timedelta,\n)\n\nimport numpy as np\nimport pytest\n\nimport pandas._testing as tm\nfrom pandas.core.indexes.api import (\n Index,\n RangeIndex,\n)\n\n\n@pytest.fixture\ndef index_large():\n # large values used in TestUInt64Index where no compat needed with int64/float64\n large = [2**63, 2**63 + 10, 2**63 + 15, 2**63 + 20, 2**63 + 25]\n return Index(large, dtype=np.uint64)\n\n\nclass TestSetOps:\n @pytest.mark.parametrize("dtype", ["f8", "u8", "i8"])\n def test_union_non_numeric(self, dtype):\n # corner case, non-numeric\n index = Index(np.arange(5, dtype=dtype), dtype=dtype)\n assert index.dtype == dtype\n\n other = Index([datetime.now() + timedelta(i) for i in range(4)], dtype=object)\n result = index.union(other)\n expected = Index(np.concatenate((index, other)))\n tm.assert_index_equal(result, expected)\n\n result = other.union(index)\n expected = Index(np.concatenate((other, index)))\n tm.assert_index_equal(result, expected)\n\n def test_intersection(self):\n index = Index(range(5), dtype=np.int64)\n\n other = Index([1, 2, 3, 4, 5])\n result = index.intersection(other)\n expected = Index(np.sort(np.intersect1d(index.values, other.values)))\n tm.assert_index_equal(result, expected)\n\n result = other.intersection(index)\n expected = Index(\n np.sort(np.asarray(np.intersect1d(index.values, other.values)))\n )\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize("dtype", ["int64", "uint64"])\n def test_int_float_union_dtype(self, dtype):\n # https://github.com/pandas-dev/pandas/issues/26778\n # [u]int | float -> float\n index = Index([0, 2, 3], dtype=dtype)\n other = Index([0.5, 1.5], dtype=np.float64)\n expected = Index([0.0, 0.5, 1.5, 2.0, 3.0], dtype=np.float64)\n result = index.union(other)\n tm.assert_index_equal(result, expected)\n\n result = other.union(index)\n tm.assert_index_equal(result, expected)\n\n def test_range_float_union_dtype(self):\n # https://github.com/pandas-dev/pandas/issues/26778\n index = RangeIndex(start=0, stop=3)\n other = Index([0.5, 1.5], dtype=np.float64)\n result = index.union(other)\n expected = Index([0.0, 0.5, 1, 1.5, 2.0], dtype=np.float64)\n tm.assert_index_equal(result, expected)\n\n result = other.union(index)\n tm.assert_index_equal(result, expected)\n\n def test_range_uint64_union_dtype(self):\n # https://github.com/pandas-dev/pandas/issues/26778\n index = RangeIndex(start=0, stop=3)\n other = Index([0, 10], dtype=np.uint64)\n result = index.union(other)\n expected = Index([0, 1, 2, 10], dtype=object)\n tm.assert_index_equal(result, expected)\n\n result = other.union(index)\n tm.assert_index_equal(result, expected)\n\n def test_float64_index_difference(self):\n # https://github.com/pandas-dev/pandas/issues/35217\n float_index = Index([1.0, 2, 3])\n string_index = Index(["1", "2", "3"])\n\n result = float_index.difference(string_index)\n tm.assert_index_equal(result, float_index)\n\n result = string_index.difference(float_index)\n tm.assert_index_equal(result, string_index)\n\n def test_intersection_uint64_outside_int64_range(self, index_large):\n other = Index([2**63, 2**63 + 5, 2**63 + 10, 2**63 + 15, 2**63 + 20])\n result = index_large.intersection(other)\n expected = Index(np.sort(np.intersect1d(index_large.values, other.values)))\n tm.assert_index_equal(result, expected)\n\n result = other.intersection(index_large)\n expected = Index(\n np.sort(np.asarray(np.intersect1d(index_large.values, other.values)))\n )\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize(\n "index2,keeps_name",\n [\n (Index([4, 7, 6, 5, 3], name="index"), True),\n (Index([4, 7, 6, 5, 3], name="other"), False),\n ],\n )\n def test_intersection_monotonic(self, index2, keeps_name, sort):\n index1 = Index([5, 3, 2, 4, 1], name="index")\n expected = Index([5, 3, 4])\n\n if keeps_name:\n expected.name = "index"\n\n result = index1.intersection(index2, sort=sort)\n if sort is None:\n expected = expected.sort_values()\n tm.assert_index_equal(result, expected)\n\n def test_symmetric_difference(self, sort):\n # smoke\n index1 = Index([5, 2, 3, 4], name="index1")\n index2 = Index([2, 3, 4, 1])\n result = index1.symmetric_difference(index2, sort=sort)\n expected = Index([5, 1])\n if sort is not None:\n tm.assert_index_equal(result, expected)\n else:\n tm.assert_index_equal(result, expected.sort_values())\n assert result.name is None\n if sort is None:\n expected = expected.sort_values()\n tm.assert_index_equal(result, expected)\n\n\nclass TestSetOpsSort:\n @pytest.mark.parametrize("slice_", [slice(None), slice(0)])\n def test_union_sort_other_special(self, slice_):\n # https://github.com/pandas-dev/pandas/issues/24959\n\n idx = Index([1, 0, 2])\n # default, sort=None\n other = idx[slice_]\n tm.assert_index_equal(idx.union(other), idx)\n tm.assert_index_equal(other.union(idx), idx)\n\n # sort=False\n tm.assert_index_equal(idx.union(other, sort=False), idx)\n\n @pytest.mark.parametrize("slice_", [slice(None), slice(0)])\n def test_union_sort_special_true(self, slice_):\n idx = Index([1, 0, 2])\n # default, sort=None\n other = idx[slice_]\n\n result = idx.union(other, sort=True)\n expected = Index([0, 1, 2])\n tm.assert_index_equal(result, expected)\n | .venv\Lib\site-packages\pandas\tests\indexes\numeric\test_setops.py | test_setops.py | Python | 5,874 | 0.95 | 0.113095 | 0.088235 | node-utils | 372 | 2024-09-16T21:06:03.735707 | MIT | true | afc7354d3ca2bed6c64f97e7c3230b1c |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\numeric\__pycache__\test_astype.cpython-313.pyc | test_astype.cpython-313.pyc | Other | 6,791 | 0.8 | 0 | 0 | awesome-app | 946 | 2025-05-24T15:38:18.894219 | BSD-3-Clause | true | 13262b09ab8991b813117e5d65a067b3 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\numeric\__pycache__\test_indexing.cpython-313.pyc | test_indexing.cpython-313.pyc | Other | 42,961 | 0.95 | 0.00641 | 0 | node-utils | 719 | 2024-07-04T21:01:00.745985 | BSD-3-Clause | true | 35f0106dffa79fff45fefee0c60493fb |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\numeric\__pycache__\test_join.cpython-313.pyc | test_join.cpython-313.pyc | Other | 22,701 | 0.8 | 0 | 0 | python-kit | 70 | 2025-01-02T22:07:42.318193 | MIT | true | 95f4116ceb035e30763f2764eea15160 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\numeric\__pycache__\test_numeric.cpython-313.pyc | test_numeric.cpython-313.pyc | Other | 31,099 | 0.8 | 0.004854 | 0.005076 | vue-tools | 839 | 2023-09-15T16:15:08.282546 | GPL-3.0 | true | e07e2816869d9daf772eaa8102b92fbb |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\numeric\__pycache__\test_setops.cpython-313.pyc | test_setops.cpython-313.pyc | Other | 9,882 | 0.8 | 0 | 0 | awesome-app | 256 | 2024-10-26T18:48:37.039757 | MIT | true | 1a10f22902af786877ab6f403dd8aae6 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\numeric\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 203 | 0.7 | 0 | 0 | react-lib | 41 | 2024-11-25T14:48:29.508770 | MIT | true | edd16ba1e42f38e451e5f44089988e60 |
import pytest\n\nfrom pandas import (\n Index,\n NaT,\n)\n\n\ndef test_astype_invalid_nas_to_tdt64_raises():\n # GH#45722 don't cast np.datetime64 NaTs to timedelta64 NaT\n idx = Index([NaT.asm8] * 2, dtype=object)\n\n msg = r"Invalid type for timedelta scalar: <class 'numpy.datetime64'>"\n with pytest.raises(TypeError, match=msg):\n idx.astype("m8[ns]")\n | .venv\Lib\site-packages\pandas\tests\indexes\object\test_astype.py | test_astype.py | Python | 368 | 0.95 | 0.2 | 0.090909 | react-lib | 842 | 2024-02-05T19:14:31.465184 | Apache-2.0 | true | a528830992405a78f03325c4086cf227 |
from decimal import Decimal\n\nimport numpy as np\nimport pytest\n\nfrom pandas._libs.missing import is_matching_na\n\nfrom pandas import Index\nimport pandas._testing as tm\n\n\nclass TestGetIndexer:\n @pytest.mark.parametrize(\n "method,expected",\n [\n ("pad", np.array([-1, 0, 1, 1], dtype=np.intp)),\n ("backfill", np.array([0, 0, 1, -1], dtype=np.intp)),\n ],\n )\n def test_get_indexer_strings(self, method, expected):\n expected = np.array(expected, dtype=np.intp)\n index = Index(["b", "c"], dtype=object)\n actual = index.get_indexer(["a", "b", "c", "d"], method=method)\n\n tm.assert_numpy_array_equal(actual, expected)\n\n def test_get_indexer_strings_raises(self):\n index = Index(["b", "c"], dtype=object)\n\n msg = "|".join(\n [\n "operation 'sub' not supported for dtype 'str'",\n r"unsupported operand type\(s\) for -: 'str' and 'str'",\n ]\n )\n with pytest.raises(TypeError, match=msg):\n index.get_indexer(["a", "b", "c", "d"], method="nearest")\n\n with pytest.raises(TypeError, match=msg):\n index.get_indexer(["a", "b", "c", "d"], method="pad", tolerance=2)\n\n with pytest.raises(TypeError, match=msg):\n index.get_indexer(\n ["a", "b", "c", "d"], method="pad", tolerance=[2, 2, 2, 2]\n )\n\n def test_get_indexer_with_NA_values(\n self, unique_nulls_fixture, unique_nulls_fixture2\n ):\n # GH#22332\n # check pairwise, that no pair of na values\n # is mangled\n if unique_nulls_fixture is unique_nulls_fixture2:\n return # skip it, values are not unique\n arr = np.array([unique_nulls_fixture, unique_nulls_fixture2], dtype=object)\n index = Index(arr, dtype=object)\n result = index.get_indexer(\n Index(\n [unique_nulls_fixture, unique_nulls_fixture2, "Unknown"], dtype=object\n )\n )\n expected = np.array([0, 1, -1], dtype=np.intp)\n tm.assert_numpy_array_equal(result, expected)\n\n def test_get_indexer_infer_string_missing_values(self):\n # ensure the passed list is not cast to string but to object so that\n # the None value is matched in the index\n # https://github.com/pandas-dev/pandas/issues/55834\n idx = Index(["a", "b", None], dtype="object")\n result = idx.get_indexer([None, "x"])\n expected = np.array([2, -1], dtype=np.intp)\n tm.assert_numpy_array_equal(result, expected)\n\n\nclass TestGetIndexerNonUnique:\n def test_get_indexer_non_unique_nas(self, nulls_fixture):\n # even though this isn't non-unique, this should still work\n index = Index(["a", "b", nulls_fixture], dtype=object)\n indexer, missing = index.get_indexer_non_unique([nulls_fixture])\n\n expected_indexer = np.array([2], dtype=np.intp)\n expected_missing = np.array([], dtype=np.intp)\n tm.assert_numpy_array_equal(indexer, expected_indexer)\n tm.assert_numpy_array_equal(missing, expected_missing)\n\n # actually non-unique\n index = Index(["a", nulls_fixture, "b", nulls_fixture], dtype=object)\n indexer, missing = index.get_indexer_non_unique([nulls_fixture])\n\n expected_indexer = np.array([1, 3], dtype=np.intp)\n tm.assert_numpy_array_equal(indexer, expected_indexer)\n tm.assert_numpy_array_equal(missing, expected_missing)\n\n # matching-but-not-identical nans\n if is_matching_na(nulls_fixture, float("NaN")):\n index = Index(["a", float("NaN"), "b", float("NaN")], dtype=object)\n match_but_not_identical = True\n elif is_matching_na(nulls_fixture, Decimal("NaN")):\n index = Index(["a", Decimal("NaN"), "b", Decimal("NaN")], dtype=object)\n match_but_not_identical = True\n else:\n match_but_not_identical = False\n\n if match_but_not_identical:\n indexer, missing = index.get_indexer_non_unique([nulls_fixture])\n\n expected_indexer = np.array([1, 3], dtype=np.intp)\n tm.assert_numpy_array_equal(indexer, expected_indexer)\n tm.assert_numpy_array_equal(missing, expected_missing)\n\n @pytest.mark.filterwarnings("ignore:elementwise comp:DeprecationWarning")\n def test_get_indexer_non_unique_np_nats(self, np_nat_fixture, np_nat_fixture2):\n expected_missing = np.array([], dtype=np.intp)\n # matching-but-not-identical nats\n if is_matching_na(np_nat_fixture, np_nat_fixture2):\n # ensure nats are different objects\n index = Index(\n np.array(\n ["2021-10-02", np_nat_fixture.copy(), np_nat_fixture2.copy()],\n dtype=object,\n ),\n dtype=object,\n )\n # pass as index to prevent target from being casted to DatetimeIndex\n indexer, missing = index.get_indexer_non_unique(\n Index([np_nat_fixture], dtype=object)\n )\n expected_indexer = np.array([1, 2], dtype=np.intp)\n tm.assert_numpy_array_equal(indexer, expected_indexer)\n tm.assert_numpy_array_equal(missing, expected_missing)\n # dt64nat vs td64nat\n else:\n try:\n np_nat_fixture == np_nat_fixture2\n except (TypeError, OverflowError):\n # Numpy will raise on uncomparable types, like\n # np.datetime64('NaT', 'Y') and np.datetime64('NaT', 'ps')\n # https://github.com/numpy/numpy/issues/22762\n return\n index = Index(\n np.array(\n [\n "2021-10-02",\n np_nat_fixture,\n np_nat_fixture2,\n np_nat_fixture,\n np_nat_fixture2,\n ],\n dtype=object,\n ),\n dtype=object,\n )\n # pass as index to prevent target from being casted to DatetimeIndex\n indexer, missing = index.get_indexer_non_unique(\n Index([np_nat_fixture], dtype=object)\n )\n expected_indexer = np.array([1, 3], dtype=np.intp)\n tm.assert_numpy_array_equal(indexer, expected_indexer)\n tm.assert_numpy_array_equal(missing, expected_missing)\n | .venv\Lib\site-packages\pandas\tests\indexes\object\test_indexing.py | test_indexing.py | Python | 6,442 | 0.95 | 0.09434 | 0.123188 | node-utils | 884 | 2024-08-31T22:26:22.077861 | BSD-3-Clause | true | a5103e5074e3226976cdf43d042f4583 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\object\__pycache__\test_astype.cpython-313.pyc | test_astype.cpython-313.pyc | Other | 846 | 0.85 | 0.166667 | 0 | react-lib | 797 | 2025-05-11T05:21:18.908540 | Apache-2.0 | true | ee8a7bec529d05044e87079d44a18669 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\object\__pycache__\test_indexing.cpython-313.pyc | test_indexing.cpython-313.pyc | Other | 7,731 | 0.8 | 0.027778 | 0 | vue-tools | 218 | 2023-07-18T12:24:32.202321 | BSD-3-Clause | true | e7af277b5babbdf2f12c951631f5894e |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\object\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 202 | 0.7 | 0 | 0 | vue-tools | 850 | 2025-02-15T00:58:11.169163 | MIT | true | bf4807f2a7c9dcb3fb58ec58794447c2 |
import numpy as np\nimport pytest\n\nfrom pandas._libs.tslibs.period import IncompatibleFrequency\n\nfrom pandas.core.dtypes.dtypes import PeriodDtype\n\nfrom pandas import (\n Index,\n NaT,\n Period,\n PeriodIndex,\n Series,\n date_range,\n offsets,\n period_range,\n)\nimport pandas._testing as tm\nfrom pandas.core.arrays import PeriodArray\n\n\nclass TestPeriodIndexDisallowedFreqs:\n @pytest.mark.parametrize(\n "freq,freq_depr",\n [\n ("2M", "2ME"),\n ("2Q-MAR", "2QE-MAR"),\n ("2Y-FEB", "2YE-FEB"),\n ("2M", "2me"),\n ("2Q-MAR", "2qe-MAR"),\n ("2Y-FEB", "2yE-feb"),\n ],\n )\n def test_period_index_offsets_frequency_error_message(self, freq, freq_depr):\n # GH#52064\n msg = f"for Period, please use '{freq[1:]}' instead of '{freq_depr[1:]}'"\n\n with pytest.raises(ValueError, match=msg):\n PeriodIndex(["2020-01-01", "2020-01-02"], freq=freq_depr)\n\n with pytest.raises(ValueError, match=msg):\n period_range(start="2020-01-01", end="2020-01-02", freq=freq_depr)\n\n @pytest.mark.parametrize("freq_depr", ["2SME", "2sme", "2CBME", "2BYE", "2Bye"])\n def test_period_index_frequency_invalid_freq(self, freq_depr):\n # GH#9586\n msg = f"Invalid frequency: {freq_depr[1:]}"\n\n with pytest.raises(ValueError, match=msg):\n period_range("2020-01", "2020-05", freq=freq_depr)\n with pytest.raises(ValueError, match=msg):\n PeriodIndex(["2020-01", "2020-05"], freq=freq_depr)\n\n @pytest.mark.parametrize("freq", ["2BQE-SEP", "2BYE-MAR", "2BME"])\n def test_period_index_from_datetime_index_invalid_freq(self, freq):\n # GH#56899\n msg = f"Invalid frequency: {freq[1:]}"\n\n rng = date_range("01-Jan-2012", periods=8, freq=freq)\n with pytest.raises(ValueError, match=msg):\n rng.to_period()\n\n\nclass TestPeriodIndex:\n def test_from_ordinals(self):\n Period(ordinal=-1000, freq="Y")\n Period(ordinal=0, freq="Y")\n\n msg = "The 'ordinal' keyword in PeriodIndex is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n idx1 = PeriodIndex(ordinal=[-1, 0, 1], freq="Y")\n with tm.assert_produces_warning(FutureWarning, match=msg):\n idx2 = PeriodIndex(ordinal=np.array([-1, 0, 1]), freq="Y")\n tm.assert_index_equal(idx1, idx2)\n\n alt1 = PeriodIndex.from_ordinals([-1, 0, 1], freq="Y")\n tm.assert_index_equal(alt1, idx1)\n\n alt2 = PeriodIndex.from_ordinals(np.array([-1, 0, 1]), freq="Y")\n tm.assert_index_equal(alt2, idx2)\n\n def test_keyword_mismatch(self):\n # GH#55961 we should get exactly one of data/ordinals/**fields\n per = Period("2016-01-01", "D")\n depr_msg1 = "The 'ordinal' keyword in PeriodIndex is deprecated"\n depr_msg2 = "Constructing PeriodIndex from fields is deprecated"\n\n err_msg1 = "Cannot pass both data and ordinal"\n with pytest.raises(ValueError, match=err_msg1):\n with tm.assert_produces_warning(FutureWarning, match=depr_msg1):\n PeriodIndex(data=[per], ordinal=[per.ordinal], freq=per.freq)\n\n err_msg2 = "Cannot pass both data and fields"\n with pytest.raises(ValueError, match=err_msg2):\n with tm.assert_produces_warning(FutureWarning, match=depr_msg2):\n PeriodIndex(data=[per], year=[per.year], freq=per.freq)\n\n err_msg3 = "Cannot pass both ordinal and fields"\n with pytest.raises(ValueError, match=err_msg3):\n with tm.assert_produces_warning(FutureWarning, match=depr_msg2):\n PeriodIndex(ordinal=[per.ordinal], year=[per.year], freq=per.freq)\n\n def test_construction_base_constructor(self):\n # GH 13664\n arr = [Period("2011-01", freq="M"), NaT, Period("2011-03", freq="M")]\n tm.assert_index_equal(Index(arr), PeriodIndex(arr))\n tm.assert_index_equal(Index(np.array(arr)), PeriodIndex(np.array(arr)))\n\n arr = [np.nan, NaT, Period("2011-03", freq="M")]\n tm.assert_index_equal(Index(arr), PeriodIndex(arr))\n tm.assert_index_equal(Index(np.array(arr)), PeriodIndex(np.array(arr)))\n\n arr = [Period("2011-01", freq="M"), NaT, Period("2011-03", freq="D")]\n tm.assert_index_equal(Index(arr), Index(arr, dtype=object))\n\n tm.assert_index_equal(Index(np.array(arr)), Index(np.array(arr), dtype=object))\n\n def test_base_constructor_with_period_dtype(self):\n dtype = PeriodDtype("D")\n values = ["2011-01-01", "2012-03-04", "2014-05-01"]\n result = Index(values, dtype=dtype)\n\n expected = PeriodIndex(values, dtype=dtype)\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize(\n "values_constructor", [list, np.array, PeriodIndex, PeriodArray._from_sequence]\n )\n def test_index_object_dtype(self, values_constructor):\n # Index(periods, dtype=object) is an Index (not an PeriodIndex)\n periods = [\n Period("2011-01", freq="M"),\n NaT,\n Period("2011-03", freq="M"),\n ]\n values = values_constructor(periods)\n result = Index(values, dtype=object)\n\n assert type(result) is Index\n tm.assert_numpy_array_equal(result.values, np.array(values))\n\n def test_constructor_use_start_freq(self):\n # GH #1118\n msg1 = "Period with BDay freq is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg1):\n p = Period("4/2/2012", freq="B")\n msg2 = r"PeriodDtype\[B\] is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg2):\n expected = period_range(start="4/2/2012", periods=10, freq="B")\n\n with tm.assert_produces_warning(FutureWarning, match=msg2):\n index = period_range(start=p, periods=10)\n tm.assert_index_equal(index, expected)\n\n def test_constructor_field_arrays(self):\n # GH #1264\n\n years = np.arange(1990, 2010).repeat(4)[2:-2]\n quarters = np.tile(np.arange(1, 5), 20)[2:-2]\n\n depr_msg = "Constructing PeriodIndex from fields is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n index = PeriodIndex(year=years, quarter=quarters, freq="Q-DEC")\n expected = period_range("1990Q3", "2009Q2", freq="Q-DEC")\n tm.assert_index_equal(index, expected)\n\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n index2 = PeriodIndex(year=years, quarter=quarters, freq="2Q-DEC")\n tm.assert_numpy_array_equal(index.asi8, index2.asi8)\n\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n index = PeriodIndex(year=years, quarter=quarters)\n tm.assert_index_equal(index, expected)\n\n years = [2007, 2007, 2007]\n months = [1, 2]\n\n msg = "Mismatched Period array lengths"\n with pytest.raises(ValueError, match=msg):\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n PeriodIndex(year=years, month=months, freq="M")\n with pytest.raises(ValueError, match=msg):\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n PeriodIndex(year=years, month=months, freq="2M")\n\n years = [2007, 2007, 2007]\n months = [1, 2, 3]\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n idx = PeriodIndex(year=years, month=months, freq="M")\n exp = period_range("2007-01", periods=3, freq="M")\n tm.assert_index_equal(idx, exp)\n\n def test_constructor_nano(self):\n idx = period_range(\n start=Period(ordinal=1, freq="ns"),\n end=Period(ordinal=4, freq="ns"),\n freq="ns",\n )\n exp = PeriodIndex(\n [\n Period(ordinal=1, freq="ns"),\n Period(ordinal=2, freq="ns"),\n Period(ordinal=3, freq="ns"),\n Period(ordinal=4, freq="ns"),\n ],\n freq="ns",\n )\n tm.assert_index_equal(idx, exp)\n\n def test_constructor_arrays_negative_year(self):\n years = np.arange(1960, 2000, dtype=np.int64).repeat(4)\n quarters = np.tile(np.array([1, 2, 3, 4], dtype=np.int64), 40)\n\n msg = "Constructing PeriodIndex from fields is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n pindex = PeriodIndex(year=years, quarter=quarters)\n\n tm.assert_index_equal(pindex.year, Index(years))\n tm.assert_index_equal(pindex.quarter, Index(quarters))\n\n alt = PeriodIndex.from_fields(year=years, quarter=quarters)\n tm.assert_index_equal(alt, pindex)\n\n def test_constructor_invalid_quarters(self):\n depr_msg = "Constructing PeriodIndex from fields is deprecated"\n msg = "Quarter must be 1 <= q <= 4"\n with pytest.raises(ValueError, match=msg):\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n PeriodIndex(\n year=range(2000, 2004), quarter=list(range(4)), freq="Q-DEC"\n )\n\n def test_period_range_fractional_period(self):\n msg = "Non-integer 'periods' in pd.date_range, pd.timedelta_range"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = period_range("2007-01", periods=10.5, freq="M")\n exp = period_range("2007-01", periods=10, freq="M")\n tm.assert_index_equal(result, exp)\n\n def test_constructor_with_without_freq(self):\n # GH53687\n start = Period("2002-01-01 00:00", freq="30min")\n exp = period_range(start=start, periods=5, freq=start.freq)\n result = period_range(start=start, periods=5)\n tm.assert_index_equal(exp, result)\n\n def test_constructor_fromarraylike(self):\n idx = period_range("2007-01", periods=20, freq="M")\n\n # values is an array of Period, thus can retrieve freq\n tm.assert_index_equal(PeriodIndex(idx.values), idx)\n tm.assert_index_equal(PeriodIndex(list(idx.values)), idx)\n\n msg = "freq not specified and cannot be inferred"\n with pytest.raises(ValueError, match=msg):\n PeriodIndex(idx.asi8)\n with pytest.raises(ValueError, match=msg):\n PeriodIndex(list(idx.asi8))\n\n msg = "'Period' object is not iterable"\n with pytest.raises(TypeError, match=msg):\n PeriodIndex(data=Period("2007", freq="Y"))\n\n result = PeriodIndex(iter(idx))\n tm.assert_index_equal(result, idx)\n\n result = PeriodIndex(idx)\n tm.assert_index_equal(result, idx)\n\n result = PeriodIndex(idx, freq="M")\n tm.assert_index_equal(result, idx)\n\n result = PeriodIndex(idx, freq=offsets.MonthEnd())\n tm.assert_index_equal(result, idx)\n assert result.freq == "ME"\n\n result = PeriodIndex(idx, freq="2M")\n tm.assert_index_equal(result, idx.asfreq("2M"))\n assert result.freq == "2ME"\n\n result = PeriodIndex(idx, freq=offsets.MonthEnd(2))\n tm.assert_index_equal(result, idx.asfreq("2M"))\n assert result.freq == "2ME"\n\n result = PeriodIndex(idx, freq="D")\n exp = idx.asfreq("D", "e")\n tm.assert_index_equal(result, exp)\n\n def test_constructor_datetime64arr(self):\n vals = np.arange(100000, 100000 + 10000, 100, dtype=np.int64)\n vals = vals.view(np.dtype("M8[us]"))\n\n pi = PeriodIndex(vals, freq="D")\n\n expected = PeriodIndex(vals.astype("M8[ns]"), freq="D")\n tm.assert_index_equal(pi, expected)\n\n @pytest.mark.parametrize("box", [None, "series", "index"])\n def test_constructor_datetime64arr_ok(self, box):\n # https://github.com/pandas-dev/pandas/issues/23438\n data = date_range("2017", periods=4, freq="ME")\n if box is None:\n data = data._values\n elif box == "series":\n data = Series(data)\n\n result = PeriodIndex(data, freq="D")\n expected = PeriodIndex(\n ["2017-01-31", "2017-02-28", "2017-03-31", "2017-04-30"], freq="D"\n )\n tm.assert_index_equal(result, expected)\n\n def test_constructor_dtype(self):\n # passing a dtype with a tz should localize\n idx = PeriodIndex(["2013-01", "2013-03"], dtype="period[M]")\n exp = PeriodIndex(["2013-01", "2013-03"], freq="M")\n tm.assert_index_equal(idx, exp)\n assert idx.dtype == "period[M]"\n\n idx = PeriodIndex(["2013-01-05", "2013-03-05"], dtype="period[3D]")\n exp = PeriodIndex(["2013-01-05", "2013-03-05"], freq="3D")\n tm.assert_index_equal(idx, exp)\n assert idx.dtype == "period[3D]"\n\n # if we already have a freq and its not the same, then asfreq\n # (not changed)\n idx = PeriodIndex(["2013-01-01", "2013-01-02"], freq="D")\n\n res = PeriodIndex(idx, dtype="period[M]")\n exp = PeriodIndex(["2013-01", "2013-01"], freq="M")\n tm.assert_index_equal(res, exp)\n assert res.dtype == "period[M]"\n\n res = PeriodIndex(idx, freq="M")\n tm.assert_index_equal(res, exp)\n assert res.dtype == "period[M]"\n\n msg = "specified freq and dtype are different"\n with pytest.raises(IncompatibleFrequency, match=msg):\n PeriodIndex(["2011-01"], freq="M", dtype="period[D]")\n\n def test_constructor_empty(self):\n idx = PeriodIndex([], freq="M")\n assert isinstance(idx, PeriodIndex)\n assert len(idx) == 0\n assert idx.freq == "ME"\n\n with pytest.raises(ValueError, match="freq not specified"):\n PeriodIndex([])\n\n def test_constructor_pi_nat(self):\n idx = PeriodIndex(\n [Period("2011-01", freq="M"), NaT, Period("2011-01", freq="M")]\n )\n exp = PeriodIndex(["2011-01", "NaT", "2011-01"], freq="M")\n tm.assert_index_equal(idx, exp)\n\n idx = PeriodIndex(\n np.array([Period("2011-01", freq="M"), NaT, Period("2011-01", freq="M")])\n )\n tm.assert_index_equal(idx, exp)\n\n idx = PeriodIndex(\n [NaT, NaT, Period("2011-01", freq="M"), Period("2011-01", freq="M")]\n )\n exp = PeriodIndex(["NaT", "NaT", "2011-01", "2011-01"], freq="M")\n tm.assert_index_equal(idx, exp)\n\n idx = PeriodIndex(\n np.array(\n [NaT, NaT, Period("2011-01", freq="M"), Period("2011-01", freq="M")]\n )\n )\n tm.assert_index_equal(idx, exp)\n\n idx = PeriodIndex([NaT, NaT, "2011-01", "2011-01"], freq="M")\n tm.assert_index_equal(idx, exp)\n\n with pytest.raises(ValueError, match="freq not specified"):\n PeriodIndex([NaT, NaT])\n\n with pytest.raises(ValueError, match="freq not specified"):\n PeriodIndex(np.array([NaT, NaT]))\n\n with pytest.raises(ValueError, match="freq not specified"):\n PeriodIndex(["NaT", "NaT"])\n\n with pytest.raises(ValueError, match="freq not specified"):\n PeriodIndex(np.array(["NaT", "NaT"]))\n\n def test_constructor_incompat_freq(self):\n msg = "Input has different freq=D from PeriodIndex\\(freq=M\\)"\n\n with pytest.raises(IncompatibleFrequency, match=msg):\n PeriodIndex([Period("2011-01", freq="M"), NaT, Period("2011-01", freq="D")])\n\n with pytest.raises(IncompatibleFrequency, match=msg):\n PeriodIndex(\n np.array(\n [Period("2011-01", freq="M"), NaT, Period("2011-01", freq="D")]\n )\n )\n\n # first element is NaT\n with pytest.raises(IncompatibleFrequency, match=msg):\n PeriodIndex([NaT, Period("2011-01", freq="M"), Period("2011-01", freq="D")])\n\n with pytest.raises(IncompatibleFrequency, match=msg):\n PeriodIndex(\n np.array(\n [NaT, Period("2011-01", freq="M"), Period("2011-01", freq="D")]\n )\n )\n\n def test_constructor_mixed(self):\n idx = PeriodIndex(["2011-01", NaT, Period("2011-01", freq="M")])\n exp = PeriodIndex(["2011-01", "NaT", "2011-01"], freq="M")\n tm.assert_index_equal(idx, exp)\n\n idx = PeriodIndex(["NaT", NaT, Period("2011-01", freq="M")])\n exp = PeriodIndex(["NaT", "NaT", "2011-01"], freq="M")\n tm.assert_index_equal(idx, exp)\n\n idx = PeriodIndex([Period("2011-01-01", freq="D"), NaT, "2012-01-01"])\n exp = PeriodIndex(["2011-01-01", "NaT", "2012-01-01"], freq="D")\n tm.assert_index_equal(idx, exp)\n\n @pytest.mark.parametrize("floats", [[1.1, 2.1], np.array([1.1, 2.1])])\n def test_constructor_floats(self, floats):\n msg = "PeriodIndex does not allow floating point in construction"\n with pytest.raises(TypeError, match=msg):\n PeriodIndex(floats)\n\n def test_constructor_year_and_quarter(self):\n year = Series([2001, 2002, 2003])\n quarter = year - 2000\n msg = "Constructing PeriodIndex from fields is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n idx = PeriodIndex(year=year, quarter=quarter)\n strs = [f"{t[0]:d}Q{t[1]:d}" for t in zip(quarter, year)]\n lops = list(map(Period, strs))\n p = PeriodIndex(lops)\n tm.assert_index_equal(p, idx)\n\n def test_constructor_freq_mult(self):\n # GH #7811\n pidx = period_range(start="2014-01", freq="2M", periods=4)\n expected = PeriodIndex(["2014-01", "2014-03", "2014-05", "2014-07"], freq="2M")\n tm.assert_index_equal(pidx, expected)\n\n pidx = period_range(start="2014-01-02", end="2014-01-15", freq="3D")\n expected = PeriodIndex(\n ["2014-01-02", "2014-01-05", "2014-01-08", "2014-01-11", "2014-01-14"],\n freq="3D",\n )\n tm.assert_index_equal(pidx, expected)\n\n pidx = period_range(end="2014-01-01 17:00", freq="4h", periods=3)\n expected = PeriodIndex(\n ["2014-01-01 09:00", "2014-01-01 13:00", "2014-01-01 17:00"], freq="4h"\n )\n tm.assert_index_equal(pidx, expected)\n\n msg = "Frequency must be positive, because it represents span: -1M"\n with pytest.raises(ValueError, match=msg):\n PeriodIndex(["2011-01"], freq="-1M")\n\n msg = "Frequency must be positive, because it represents span: 0M"\n with pytest.raises(ValueError, match=msg):\n PeriodIndex(["2011-01"], freq="0M")\n\n msg = "Frequency must be positive, because it represents span: 0M"\n with pytest.raises(ValueError, match=msg):\n period_range("2011-01", periods=3, freq="0M")\n\n @pytest.mark.parametrize(\n "freq_offset, freq_period",\n [\n ("YE", "Y"),\n ("ME", "M"),\n ("D", "D"),\n ("min", "min"),\n ("s", "s"),\n ],\n )\n @pytest.mark.parametrize("mult", [1, 2, 3, 4, 5])\n def test_constructor_freq_mult_dti_compat(self, mult, freq_offset, freq_period):\n freqstr_offset = str(mult) + freq_offset\n freqstr_period = str(mult) + freq_period\n pidx = period_range(start="2014-04-01", freq=freqstr_period, periods=10)\n expected = date_range(\n start="2014-04-01", freq=freqstr_offset, periods=10\n ).to_period(freqstr_period)\n tm.assert_index_equal(pidx, expected)\n\n @pytest.mark.parametrize("mult", [1, 2, 3, 4, 5])\n def test_constructor_freq_mult_dti_compat_month(self, mult):\n pidx = period_range(start="2014-04-01", freq=f"{mult}M", periods=10)\n expected = date_range(\n start="2014-04-01", freq=f"{mult}ME", periods=10\n ).to_period(f"{mult}M")\n tm.assert_index_equal(pidx, expected)\n\n def test_constructor_freq_combined(self):\n for freq in ["1D1h", "1h1D"]:\n pidx = PeriodIndex(["2016-01-01", "2016-01-02"], freq=freq)\n expected = PeriodIndex(["2016-01-01 00:00", "2016-01-02 00:00"], freq="25h")\n for freq in ["1D1h", "1h1D"]:\n pidx = period_range(start="2016-01-01", periods=2, freq=freq)\n expected = PeriodIndex(["2016-01-01 00:00", "2016-01-02 01:00"], freq="25h")\n tm.assert_index_equal(pidx, expected)\n\n def test_period_range_length(self):\n pi = period_range(freq="Y", start="1/1/2001", end="12/1/2009")\n assert len(pi) == 9\n\n pi = period_range(freq="Q", start="1/1/2001", end="12/1/2009")\n assert len(pi) == 4 * 9\n\n pi = period_range(freq="M", start="1/1/2001", end="12/1/2009")\n assert len(pi) == 12 * 9\n\n pi = period_range(freq="D", start="1/1/2001", end="12/31/2009")\n assert len(pi) == 365 * 9 + 2\n\n msg = "Period with BDay freq is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n pi = period_range(freq="B", start="1/1/2001", end="12/31/2009")\n assert len(pi) == 261 * 9\n\n pi = period_range(freq="h", start="1/1/2001", end="12/31/2001 23:00")\n assert len(pi) == 365 * 24\n\n pi = period_range(freq="Min", start="1/1/2001", end="1/1/2001 23:59")\n assert len(pi) == 24 * 60\n\n pi = period_range(freq="s", start="1/1/2001", end="1/1/2001 23:59:59")\n assert len(pi) == 24 * 60 * 60\n\n with tm.assert_produces_warning(FutureWarning, match=msg):\n start = Period("02-Apr-2005", "B")\n i1 = period_range(start=start, periods=20)\n assert len(i1) == 20\n assert i1.freq == start.freq\n assert i1[0] == start\n\n end_intv = Period("2006-12-31", "W")\n i1 = period_range(end=end_intv, periods=10)\n assert len(i1) == 10\n assert i1.freq == end_intv.freq\n assert i1[-1] == end_intv\n\n msg = "'w' is deprecated and will be removed in a future version."\n with tm.assert_produces_warning(FutureWarning, match=msg):\n end_intv = Period("2006-12-31", "1w")\n i2 = period_range(end=end_intv, periods=10)\n assert len(i1) == len(i2)\n assert (i1 == i2).all()\n assert i1.freq == i2.freq\n\n def test_infer_freq_from_first_element(self):\n msg = "Period with BDay freq is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n start = Period("02-Apr-2005", "B")\n end_intv = Period("2005-05-01", "B")\n period_range(start=start, end=end_intv)\n\n # infer freq from first element\n i2 = PeriodIndex([end_intv, Period("2005-05-05", "B")])\n assert len(i2) == 2\n assert i2[0] == end_intv\n\n with tm.assert_produces_warning(FutureWarning, match=msg):\n i2 = PeriodIndex(np.array([end_intv, Period("2005-05-05", "B")]))\n assert len(i2) == 2\n assert i2[0] == end_intv\n\n def test_mixed_freq_raises(self):\n # Mixed freq should fail\n msg = "Period with BDay freq is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n end_intv = Period("2005-05-01", "B")\n\n msg = "'w' is deprecated and will be removed in a future version."\n with tm.assert_produces_warning(FutureWarning, match=msg):\n vals = [end_intv, Period("2006-12-31", "w")]\n msg = r"Input has different freq=W-SUN from PeriodIndex\(freq=B\)"\n depr_msg = r"PeriodDtype\[B\] is deprecated"\n with pytest.raises(IncompatibleFrequency, match=msg):\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n PeriodIndex(vals)\n vals = np.array(vals)\n with pytest.raises(IncompatibleFrequency, match=msg):\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n PeriodIndex(vals)\n\n @pytest.mark.parametrize(\n "freq", ["M", "Q", "Y", "D", "B", "min", "s", "ms", "us", "ns", "h"]\n )\n @pytest.mark.filterwarnings(\n r"ignore:Period with BDay freq is deprecated:FutureWarning"\n )\n @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")\n def test_recreate_from_data(self, freq):\n org = period_range(start="2001/04/01", freq=freq, periods=1)\n idx = PeriodIndex(org.values, freq=freq)\n tm.assert_index_equal(idx, org)\n\n def test_map_with_string_constructor(self):\n raw = [2005, 2007, 2009]\n index = PeriodIndex(raw, freq="Y")\n\n expected = Index([str(num) for num in raw])\n res = index.map(str)\n\n # should return an Index\n assert isinstance(res, Index)\n\n # preserve element types\n assert all(isinstance(resi, str) for resi in res)\n\n # lastly, values should compare equal\n tm.assert_index_equal(res, expected)\n\n\nclass TestSimpleNew:\n def test_constructor_simple_new(self):\n idx = period_range("2007-01", name="p", periods=2, freq="M")\n\n with pytest.raises(AssertionError, match="<class .*PeriodIndex'>"):\n idx._simple_new(idx, name="p")\n\n result = idx._simple_new(idx._data, name="p")\n tm.assert_index_equal(result, idx)\n\n msg = "Should be numpy array of type i8"\n with pytest.raises(AssertionError, match=msg):\n # Need ndarray, not int64 Index\n type(idx._data)._simple_new(Index(idx.asi8), dtype=idx.dtype)\n\n arr = type(idx._data)._simple_new(idx.asi8, dtype=idx.dtype)\n result = idx._simple_new(arr, name="p")\n tm.assert_index_equal(result, idx)\n\n def test_constructor_simple_new_empty(self):\n # GH13079\n idx = PeriodIndex([], freq="M", name="p")\n with pytest.raises(AssertionError, match="<class .*PeriodIndex'>"):\n idx._simple_new(idx, name="p")\n\n result = idx._simple_new(idx._data, name="p")\n tm.assert_index_equal(result, idx)\n\n @pytest.mark.parametrize("floats", [[1.1, 2.1], np.array([1.1, 2.1])])\n def test_period_index_simple_new_disallows_floats(self, floats):\n with pytest.raises(AssertionError, match="<class "):\n PeriodIndex._simple_new(floats)\n\n\nclass TestShallowCopy:\n def test_shallow_copy_empty(self):\n # GH#13067\n idx = PeriodIndex([], freq="M")\n result = idx._view()\n expected = idx\n\n tm.assert_index_equal(result, expected)\n\n def test_shallow_copy_disallow_i8(self):\n # GH#24391\n pi = period_range("2018-01-01", periods=3, freq="2D")\n with pytest.raises(AssertionError, match="ndarray"):\n pi._shallow_copy(pi.asi8)\n\n def test_shallow_copy_requires_disallow_period_index(self):\n pi = period_range("2018-01-01", periods=3, freq="2D")\n with pytest.raises(AssertionError, match="PeriodIndex"):\n pi._shallow_copy(pi)\n\n\nclass TestSeriesPeriod:\n def test_constructor_cant_cast_period(self):\n msg = "Cannot cast PeriodIndex to dtype float64"\n with pytest.raises(TypeError, match=msg):\n Series(period_range("2000-01-01", periods=10, freq="D"), dtype=float)\n\n def test_constructor_cast_object(self):\n pi = period_range("1/1/2000", periods=10)\n ser = Series(pi, dtype=PeriodDtype("D"))\n exp = Series(pi)\n tm.assert_series_equal(ser, exp)\n | .venv\Lib\site-packages\pandas\tests\indexes\period\test_constructors.py | test_constructors.py | Python | 27,175 | 0.95 | 0.083936 | 0.045126 | node-utils | 173 | 2024-06-20T18:44:27.361855 | GPL-3.0 | true | d3bd24cef6a0699ee2b182ea81a775be |
from contextlib import nullcontext\nfrom datetime import (\n datetime,\n time,\n)\nimport locale\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n PeriodIndex,\n Series,\n)\nimport pandas._testing as tm\n\n\ndef get_local_am_pm():\n """Return the AM and PM strings returned by strftime in current locale."""\n am_local = time(1).strftime("%p")\n pm_local = time(13).strftime("%p")\n return am_local, pm_local\n\n\ndef test_get_values_for_csv():\n index = PeriodIndex(["2017-01-01", "2017-01-02", "2017-01-03"], freq="D")\n\n # First, with no arguments.\n expected = np.array(["2017-01-01", "2017-01-02", "2017-01-03"], dtype=object)\n\n result = index._get_values_for_csv()\n tm.assert_numpy_array_equal(result, expected)\n\n # No NaN values, so na_rep has no effect\n result = index._get_values_for_csv(na_rep="pandas")\n tm.assert_numpy_array_equal(result, expected)\n\n # Make sure date formatting works\n expected = np.array(["01-2017-01", "01-2017-02", "01-2017-03"], dtype=object)\n\n result = index._get_values_for_csv(date_format="%m-%Y-%d")\n tm.assert_numpy_array_equal(result, expected)\n\n # NULL object handling should work\n index = PeriodIndex(["2017-01-01", pd.NaT, "2017-01-03"], freq="D")\n expected = np.array(["2017-01-01", "NaT", "2017-01-03"], dtype=object)\n\n result = index._get_values_for_csv(na_rep="NaT")\n tm.assert_numpy_array_equal(result, expected)\n\n expected = np.array(["2017-01-01", "pandas", "2017-01-03"], dtype=object)\n\n result = index._get_values_for_csv(na_rep="pandas")\n tm.assert_numpy_array_equal(result, expected)\n\n\nclass TestPeriodIndexRendering:\n def test_format_empty(self):\n # GH#35712\n empty_idx = PeriodIndex([], freq="Y")\n msg = r"PeriodIndex\.format is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n assert empty_idx.format() == []\n with tm.assert_produces_warning(FutureWarning, match=msg):\n assert empty_idx.format(name=True) == [""]\n\n @pytest.mark.parametrize("method", ["__repr__", "__str__"])\n def test_representation(self, method):\n # GH#7601\n idx1 = PeriodIndex([], freq="D")\n idx2 = PeriodIndex(["2011-01-01"], freq="D")\n idx3 = PeriodIndex(["2011-01-01", "2011-01-02"], freq="D")\n idx4 = PeriodIndex(["2011-01-01", "2011-01-02", "2011-01-03"], freq="D")\n idx5 = PeriodIndex(["2011", "2012", "2013"], freq="Y")\n idx6 = PeriodIndex(["2011-01-01 09:00", "2012-02-01 10:00", "NaT"], freq="h")\n idx7 = pd.period_range("2013Q1", periods=1, freq="Q")\n idx8 = pd.period_range("2013Q1", periods=2, freq="Q")\n idx9 = pd.period_range("2013Q1", periods=3, freq="Q")\n idx10 = PeriodIndex(["2011-01-01", "2011-02-01"], freq="3D")\n\n exp1 = "PeriodIndex([], dtype='period[D]')"\n\n exp2 = "PeriodIndex(['2011-01-01'], dtype='period[D]')"\n\n exp3 = "PeriodIndex(['2011-01-01', '2011-01-02'], dtype='period[D]')"\n\n exp4 = (\n "PeriodIndex(['2011-01-01', '2011-01-02', '2011-01-03'], "\n "dtype='period[D]')"\n )\n\n exp5 = "PeriodIndex(['2011', '2012', '2013'], dtype='period[Y-DEC]')"\n\n exp6 = (\n "PeriodIndex(['2011-01-01 09:00', '2012-02-01 10:00', 'NaT'], "\n "dtype='period[h]')"\n )\n\n exp7 = "PeriodIndex(['2013Q1'], dtype='period[Q-DEC]')"\n\n exp8 = "PeriodIndex(['2013Q1', '2013Q2'], dtype='period[Q-DEC]')"\n\n exp9 = "PeriodIndex(['2013Q1', '2013Q2', '2013Q3'], dtype='period[Q-DEC]')"\n\n exp10 = "PeriodIndex(['2011-01-01', '2011-02-01'], dtype='period[3D]')"\n\n for idx, expected in zip(\n [idx1, idx2, idx3, idx4, idx5, idx6, idx7, idx8, idx9, idx10],\n [exp1, exp2, exp3, exp4, exp5, exp6, exp7, exp8, exp9, exp10],\n ):\n result = getattr(idx, method)()\n assert result == expected\n\n # TODO: These are Series.__repr__ tests\n def test_representation_to_series(self):\n # GH#10971\n idx1 = PeriodIndex([], freq="D")\n idx2 = PeriodIndex(["2011-01-01"], freq="D")\n idx3 = PeriodIndex(["2011-01-01", "2011-01-02"], freq="D")\n idx4 = PeriodIndex(["2011-01-01", "2011-01-02", "2011-01-03"], freq="D")\n idx5 = PeriodIndex(["2011", "2012", "2013"], freq="Y")\n idx6 = PeriodIndex(["2011-01-01 09:00", "2012-02-01 10:00", "NaT"], freq="h")\n\n idx7 = pd.period_range("2013Q1", periods=1, freq="Q")\n idx8 = pd.period_range("2013Q1", periods=2, freq="Q")\n idx9 = pd.period_range("2013Q1", periods=3, freq="Q")\n\n exp1 = """Series([], dtype: period[D])"""\n\n exp2 = """0 2011-01-01\ndtype: period[D]"""\n\n exp3 = """0 2011-01-01\n1 2011-01-02\ndtype: period[D]"""\n\n exp4 = """0 2011-01-01\n1 2011-01-02\n2 2011-01-03\ndtype: period[D]"""\n\n exp5 = """0 2011\n1 2012\n2 2013\ndtype: period[Y-DEC]"""\n\n exp6 = """0 2011-01-01 09:00\n1 2012-02-01 10:00\n2 NaT\ndtype: period[h]"""\n\n exp7 = """0 2013Q1\ndtype: period[Q-DEC]"""\n\n exp8 = """0 2013Q1\n1 2013Q2\ndtype: period[Q-DEC]"""\n\n exp9 = """0 2013Q1\n1 2013Q2\n2 2013Q3\ndtype: period[Q-DEC]"""\n\n for idx, expected in zip(\n [idx1, idx2, idx3, idx4, idx5, idx6, idx7, idx8, idx9],\n [exp1, exp2, exp3, exp4, exp5, exp6, exp7, exp8, exp9],\n ):\n result = repr(Series(idx))\n assert result == expected\n\n def test_summary(self):\n # GH#9116\n idx1 = PeriodIndex([], freq="D")\n idx2 = PeriodIndex(["2011-01-01"], freq="D")\n idx3 = PeriodIndex(["2011-01-01", "2011-01-02"], freq="D")\n idx4 = PeriodIndex(["2011-01-01", "2011-01-02", "2011-01-03"], freq="D")\n idx5 = PeriodIndex(["2011", "2012", "2013"], freq="Y")\n idx6 = PeriodIndex(["2011-01-01 09:00", "2012-02-01 10:00", "NaT"], freq="h")\n\n idx7 = pd.period_range("2013Q1", periods=1, freq="Q")\n idx8 = pd.period_range("2013Q1", periods=2, freq="Q")\n idx9 = pd.period_range("2013Q1", periods=3, freq="Q")\n\n exp1 = """PeriodIndex: 0 entries\nFreq: D"""\n\n exp2 = """PeriodIndex: 1 entries, 2011-01-01 to 2011-01-01\nFreq: D"""\n\n exp3 = """PeriodIndex: 2 entries, 2011-01-01 to 2011-01-02\nFreq: D"""\n\n exp4 = """PeriodIndex: 3 entries, 2011-01-01 to 2011-01-03\nFreq: D"""\n\n exp5 = """PeriodIndex: 3 entries, 2011 to 2013\nFreq: Y-DEC"""\n\n exp6 = """PeriodIndex: 3 entries, 2011-01-01 09:00 to NaT\nFreq: h"""\n\n exp7 = """PeriodIndex: 1 entries, 2013Q1 to 2013Q1\nFreq: Q-DEC"""\n\n exp8 = """PeriodIndex: 2 entries, 2013Q1 to 2013Q2\nFreq: Q-DEC"""\n\n exp9 = """PeriodIndex: 3 entries, 2013Q1 to 2013Q3\nFreq: Q-DEC"""\n\n for idx, expected in zip(\n [idx1, idx2, idx3, idx4, idx5, idx6, idx7, idx8, idx9],\n [exp1, exp2, exp3, exp4, exp5, exp6, exp7, exp8, exp9],\n ):\n result = idx._summary()\n assert result == expected\n\n\nclass TestPeriodIndexFormat:\n def test_period_format_and_strftime_default(self):\n per = PeriodIndex([datetime(2003, 1, 1, 12), None], freq="h")\n\n # Default formatting\n msg = "PeriodIndex.format is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n formatted = per.format()\n assert formatted[0] == "2003-01-01 12:00" # default: minutes not shown\n assert formatted[1] == "NaT"\n # format is equivalent to strftime(None)...\n assert formatted[0] == per.strftime(None)[0]\n assert per.strftime(None)[1] is np.nan # ...except for NaTs\n\n # Same test with nanoseconds freq\n per = pd.period_range("2003-01-01 12:01:01.123456789", periods=2, freq="ns")\n with tm.assert_produces_warning(FutureWarning, match=msg):\n formatted = per.format()\n assert (formatted == per.strftime(None)).all()\n assert formatted[0] == "2003-01-01 12:01:01.123456789"\n assert formatted[1] == "2003-01-01 12:01:01.123456790"\n\n def test_period_custom(self):\n # GH#46252 custom formatting directives %l (ms) and %u (us)\n msg = "PeriodIndex.format is deprecated"\n\n # 3 digits\n per = pd.period_range("2003-01-01 12:01:01.123", periods=2, freq="ms")\n with tm.assert_produces_warning(FutureWarning, match=msg):\n formatted = per.format(date_format="%y %I:%M:%S (ms=%l us=%u ns=%n)")\n assert formatted[0] == "03 12:01:01 (ms=123 us=123000 ns=123000000)"\n assert formatted[1] == "03 12:01:01 (ms=124 us=124000 ns=124000000)"\n\n # 6 digits\n per = pd.period_range("2003-01-01 12:01:01.123456", periods=2, freq="us")\n with tm.assert_produces_warning(FutureWarning, match=msg):\n formatted = per.format(date_format="%y %I:%M:%S (ms=%l us=%u ns=%n)")\n assert formatted[0] == "03 12:01:01 (ms=123 us=123456 ns=123456000)"\n assert formatted[1] == "03 12:01:01 (ms=123 us=123457 ns=123457000)"\n\n # 9 digits\n per = pd.period_range("2003-01-01 12:01:01.123456789", periods=2, freq="ns")\n with tm.assert_produces_warning(FutureWarning, match=msg):\n formatted = per.format(date_format="%y %I:%M:%S (ms=%l us=%u ns=%n)")\n assert formatted[0] == "03 12:01:01 (ms=123 us=123456 ns=123456789)"\n assert formatted[1] == "03 12:01:01 (ms=123 us=123456 ns=123456790)"\n\n def test_period_tz(self):\n # Formatting periods created from a datetime with timezone.\n msg = r"PeriodIndex\.format is deprecated"\n # This timestamp is in 2013 in Europe/Paris but is 2012 in UTC\n dt = pd.to_datetime(["2013-01-01 00:00:00+01:00"], utc=True)\n\n # Converting to a period looses the timezone information\n # Since tz is currently set as utc, we'll see 2012\n with tm.assert_produces_warning(UserWarning, match="will drop timezone"):\n per = dt.to_period(freq="h")\n with tm.assert_produces_warning(FutureWarning, match=msg):\n assert per.format()[0] == "2012-12-31 23:00"\n\n # If tz is currently set as paris before conversion, we'll see 2013\n dt = dt.tz_convert("Europe/Paris")\n with tm.assert_produces_warning(UserWarning, match="will drop timezone"):\n per = dt.to_period(freq="h")\n with tm.assert_produces_warning(FutureWarning, match=msg):\n assert per.format()[0] == "2013-01-01 00:00"\n\n @pytest.mark.parametrize(\n "locale_str",\n [\n pytest.param(None, id=str(locale.getlocale())),\n "it_IT.utf8",\n "it_IT", # Note: encoding will be 'ISO8859-1'\n "zh_CN.utf8",\n "zh_CN", # Note: encoding will be 'gb2312'\n ],\n )\n def test_period_non_ascii_fmt(self, locale_str):\n # GH#46468 non-ascii char in input format string leads to wrong output\n\n # Skip if locale cannot be set\n if locale_str is not None and not tm.can_set_locale(locale_str, locale.LC_ALL):\n pytest.skip(f"Skipping as locale '{locale_str}' cannot be set on host.")\n\n # Change locale temporarily for this test.\n with tm.set_locale(locale_str, locale.LC_ALL) if locale_str else nullcontext():\n # Scalar\n per = pd.Period("2018-03-11 13:00", freq="h")\n assert per.strftime("%y é") == "18 é"\n\n # Index\n per = pd.period_range("2003-01-01 01:00:00", periods=2, freq="12h")\n msg = "PeriodIndex.format is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n formatted = per.format(date_format="%y é")\n assert formatted[0] == "03 é"\n assert formatted[1] == "03 é"\n\n @pytest.mark.parametrize(\n "locale_str",\n [\n pytest.param(None, id=str(locale.getlocale())),\n "it_IT.utf8",\n "it_IT", # Note: encoding will be 'ISO8859-1'\n "zh_CN.utf8",\n "zh_CN", # Note: encoding will be 'gb2312'\n ],\n )\n def test_period_custom_locale_directive(self, locale_str):\n # GH#46319 locale-specific directive leads to non-utf8 c strftime char* result\n\n # Skip if locale cannot be set\n if locale_str is not None and not tm.can_set_locale(locale_str, locale.LC_ALL):\n pytest.skip(f"Skipping as locale '{locale_str}' cannot be set on host.")\n\n # Change locale temporarily for this test.\n with tm.set_locale(locale_str, locale.LC_ALL) if locale_str else nullcontext():\n # Get locale-specific reference\n am_local, pm_local = get_local_am_pm()\n\n # Scalar\n per = pd.Period("2018-03-11 13:00", freq="h")\n assert per.strftime("%p") == pm_local\n\n # Index\n per = pd.period_range("2003-01-01 01:00:00", periods=2, freq="12h")\n msg = "PeriodIndex.format is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n formatted = per.format(date_format="%y %I:%M:%S%p")\n assert formatted[0] == f"03 01:00:00{am_local}"\n assert formatted[1] == f"03 01:00:00{pm_local}"\n | .venv\Lib\site-packages\pandas\tests\indexes\period\test_formats.py | test_formats.py | Python | 13,259 | 0.95 | 0.071429 | 0.115523 | node-utils | 712 | 2023-12-01T17:45:35.887068 | GPL-3.0 | true | 77c303ef37f4c0787b2f238c3909b217 |
import pytest\n\nfrom pandas.compat import PY311\n\nfrom pandas import (\n offsets,\n period_range,\n)\nimport pandas._testing as tm\n\n\nclass TestFreq:\n def test_freq_setter_deprecated(self):\n # GH#20678\n idx = period_range("2018Q1", periods=4, freq="Q")\n\n # no warning for getter\n with tm.assert_produces_warning(None):\n idx.freq\n\n # warning for setter\n msg = (\n "property 'freq' of 'PeriodArray' object has no setter"\n if PY311\n else "can't set attribute"\n )\n with pytest.raises(AttributeError, match=msg):\n idx.freq = offsets.Day()\n | .venv\Lib\site-packages\pandas\tests\indexes\period\test_freq_attr.py | test_freq_attr.py | Python | 646 | 0.95 | 0.178571 | 0.136364 | vue-tools | 847 | 2025-02-22T10:27:29.120959 | BSD-3-Clause | true | afa0d8948ee74695af42bedf65b189e1 |
from datetime import datetime\nimport re\n\nimport numpy as np\nimport pytest\n\nfrom pandas._libs.tslibs import period as libperiod\nfrom pandas.errors import InvalidIndexError\n\nimport pandas as pd\nfrom pandas import (\n DatetimeIndex,\n NaT,\n Period,\n PeriodIndex,\n Series,\n Timedelta,\n date_range,\n notna,\n period_range,\n)\nimport pandas._testing as tm\n\ndti4 = date_range("2016-01-01", periods=4)\ndti = dti4[:-1]\nrng = pd.Index(range(3))\n\n\n@pytest.fixture(\n params=[\n dti,\n dti.tz_localize("UTC"),\n dti.to_period("W"),\n dti - dti[0],\n rng,\n pd.Index([1, 2, 3]),\n pd.Index([2.0, 3.0, 4.0]),\n pd.Index([4, 5, 6], dtype="u8"),\n pd.IntervalIndex.from_breaks(dti4),\n ]\n)\ndef non_comparable_idx(request):\n # All have length 3\n return request.param\n\n\nclass TestGetItem:\n def test_getitem_slice_keeps_name(self):\n idx = period_range("20010101", periods=10, freq="D", name="bob")\n assert idx.name == idx[1:].name\n\n def test_getitem(self):\n idx1 = period_range("2011-01-01", "2011-01-31", freq="D", name="idx")\n\n for idx in [idx1]:\n result = idx[0]\n assert result == Period("2011-01-01", freq="D")\n\n result = idx[-1]\n assert result == Period("2011-01-31", freq="D")\n\n result = idx[0:5]\n expected = period_range("2011-01-01", "2011-01-05", freq="D", name="idx")\n tm.assert_index_equal(result, expected)\n assert result.freq == expected.freq\n assert result.freq == "D"\n\n result = idx[0:10:2]\n expected = PeriodIndex(\n ["2011-01-01", "2011-01-03", "2011-01-05", "2011-01-07", "2011-01-09"],\n freq="D",\n name="idx",\n )\n tm.assert_index_equal(result, expected)\n assert result.freq == expected.freq\n assert result.freq == "D"\n\n result = idx[-20:-5:3]\n expected = PeriodIndex(\n ["2011-01-12", "2011-01-15", "2011-01-18", "2011-01-21", "2011-01-24"],\n freq="D",\n name="idx",\n )\n tm.assert_index_equal(result, expected)\n assert result.freq == expected.freq\n assert result.freq == "D"\n\n result = idx[4::-1]\n expected = PeriodIndex(\n ["2011-01-05", "2011-01-04", "2011-01-03", "2011-01-02", "2011-01-01"],\n freq="D",\n name="idx",\n )\n tm.assert_index_equal(result, expected)\n assert result.freq == expected.freq\n assert result.freq == "D"\n\n def test_getitem_index(self):\n idx = period_range("2007-01", periods=10, freq="M", name="x")\n\n result = idx[[1, 3, 5]]\n exp = PeriodIndex(["2007-02", "2007-04", "2007-06"], freq="M", name="x")\n tm.assert_index_equal(result, exp)\n\n result = idx[[True, True, False, False, False, True, True, False, False, False]]\n exp = PeriodIndex(\n ["2007-01", "2007-02", "2007-06", "2007-07"], freq="M", name="x"\n )\n tm.assert_index_equal(result, exp)\n\n def test_getitem_partial(self):\n rng = period_range("2007-01", periods=50, freq="M")\n ts = Series(np.random.default_rng(2).standard_normal(len(rng)), rng)\n\n with pytest.raises(KeyError, match=r"^'2006'$"):\n ts["2006"]\n\n result = ts["2008"]\n assert (result.index.year == 2008).all()\n\n result = ts["2008":"2009"]\n assert len(result) == 24\n\n result = ts["2008-1":"2009-12"]\n assert len(result) == 24\n\n result = ts["2008Q1":"2009Q4"]\n assert len(result) == 24\n\n result = ts[:"2009"]\n assert len(result) == 36\n\n result = ts["2009":]\n assert len(result) == 50 - 24\n\n exp = result\n result = ts[24:]\n tm.assert_series_equal(exp, result)\n\n ts = pd.concat([ts[10:], ts[10:]])\n msg = "left slice bound for non-unique label: '2008'"\n with pytest.raises(KeyError, match=msg):\n ts[slice("2008", "2009")]\n\n def test_getitem_datetime(self):\n rng = period_range(start="2012-01-01", periods=10, freq="W-MON")\n ts = Series(range(len(rng)), index=rng)\n\n dt1 = datetime(2011, 10, 2)\n dt4 = datetime(2012, 4, 20)\n\n rs = ts[dt1:dt4]\n tm.assert_series_equal(rs, ts)\n\n def test_getitem_nat(self):\n idx = PeriodIndex(["2011-01", "NaT", "2011-02"], freq="M")\n assert idx[0] == Period("2011-01", freq="M")\n assert idx[1] is NaT\n\n s = Series([0, 1, 2], index=idx)\n assert s[NaT] == 1\n\n s = Series(idx, index=idx)\n assert s[Period("2011-01", freq="M")] == Period("2011-01", freq="M")\n assert s[NaT] is NaT\n\n def test_getitem_list_periods(self):\n # GH 7710\n rng = period_range(start="2012-01-01", periods=10, freq="D")\n ts = Series(range(len(rng)), index=rng)\n exp = ts.iloc[[1]]\n tm.assert_series_equal(ts[[Period("2012-01-02", freq="D")]], exp)\n\n @pytest.mark.arm_slow\n def test_getitem_seconds(self):\n # GH#6716\n didx = date_range(start="2013/01/01 09:00:00", freq="s", periods=4000)\n pidx = period_range(start="2013/01/01 09:00:00", freq="s", periods=4000)\n\n for idx in [didx, pidx]:\n # getitem against index should raise ValueError\n values = [\n "2014",\n "2013/02",\n "2013/01/02",\n "2013/02/01 9h",\n "2013/02/01 09:00",\n ]\n for val in values:\n # GH7116\n # these show deprecations as we are trying\n # to slice with non-integer indexers\n with pytest.raises(IndexError, match="only integers, slices"):\n idx[val]\n\n ser = Series(np.random.default_rng(2).random(len(idx)), index=idx)\n tm.assert_series_equal(ser["2013/01/01 10:00"], ser[3600:3660])\n tm.assert_series_equal(ser["2013/01/01 9h"], ser[:3600])\n for d in ["2013/01/01", "2013/01", "2013"]:\n tm.assert_series_equal(ser[d], ser)\n\n @pytest.mark.parametrize(\n "idx_range",\n [\n date_range,\n period_range,\n ],\n )\n def test_getitem_day(self, idx_range):\n # GH#6716\n # Confirm DatetimeIndex and PeriodIndex works identically\n # getitem against index should raise ValueError\n idx = idx_range(start="2013/01/01", freq="D", periods=400)\n values = [\n "2014",\n "2013/02",\n "2013/01/02",\n "2013/02/01 9h",\n "2013/02/01 09:00",\n ]\n for val in values:\n # GH7116\n # these show deprecations as we are trying\n # to slice with non-integer indexers\n with pytest.raises(IndexError, match="only integers, slices"):\n idx[val]\n\n ser = Series(np.random.default_rng(2).random(len(idx)), index=idx)\n tm.assert_series_equal(ser["2013/01"], ser[0:31])\n tm.assert_series_equal(ser["2013/02"], ser[31:59])\n tm.assert_series_equal(ser["2014"], ser[365:])\n\n invalid = ["2013/02/01 9h", "2013/02/01 09:00"]\n for val in invalid:\n with pytest.raises(KeyError, match=val):\n ser[val]\n\n\nclass TestGetLoc:\n def test_get_loc_msg(self):\n idx = period_range("2000-1-1", freq="Y", periods=10)\n bad_period = Period("2012", "Y")\n with pytest.raises(KeyError, match=r"^Period\('2012', 'Y-DEC'\)$"):\n idx.get_loc(bad_period)\n\n try:\n idx.get_loc(bad_period)\n except KeyError as inst:\n assert inst.args[0] == bad_period\n\n def test_get_loc_nat(self):\n didx = DatetimeIndex(["2011-01-01", "NaT", "2011-01-03"])\n pidx = PeriodIndex(["2011-01-01", "NaT", "2011-01-03"], freq="M")\n\n # check DatetimeIndex compat\n for idx in [didx, pidx]:\n assert idx.get_loc(NaT) == 1\n assert idx.get_loc(None) == 1\n assert idx.get_loc(float("nan")) == 1\n assert idx.get_loc(np.nan) == 1\n\n def test_get_loc(self):\n # GH 17717\n p0 = Period("2017-09-01")\n p1 = Period("2017-09-02")\n p2 = Period("2017-09-03")\n\n # get the location of p1/p2 from\n # monotonic increasing PeriodIndex with non-duplicate\n idx0 = PeriodIndex([p0, p1, p2])\n expected_idx1_p1 = 1\n expected_idx1_p2 = 2\n\n assert idx0.get_loc(p1) == expected_idx1_p1\n assert idx0.get_loc(str(p1)) == expected_idx1_p1\n assert idx0.get_loc(p2) == expected_idx1_p2\n assert idx0.get_loc(str(p2)) == expected_idx1_p2\n\n msg = "Cannot interpret 'foo' as period"\n with pytest.raises(KeyError, match=msg):\n idx0.get_loc("foo")\n with pytest.raises(KeyError, match=r"^1\.1$"):\n idx0.get_loc(1.1)\n\n with pytest.raises(InvalidIndexError, match=re.escape(str(idx0))):\n idx0.get_loc(idx0)\n\n # get the location of p1/p2 from\n # monotonic increasing PeriodIndex with duplicate\n idx1 = PeriodIndex([p1, p1, p2])\n expected_idx1_p1 = slice(0, 2)\n expected_idx1_p2 = 2\n\n assert idx1.get_loc(p1) == expected_idx1_p1\n assert idx1.get_loc(str(p1)) == expected_idx1_p1\n assert idx1.get_loc(p2) == expected_idx1_p2\n assert idx1.get_loc(str(p2)) == expected_idx1_p2\n\n msg = "Cannot interpret 'foo' as period"\n with pytest.raises(KeyError, match=msg):\n idx1.get_loc("foo")\n\n with pytest.raises(KeyError, match=r"^1\.1$"):\n idx1.get_loc(1.1)\n\n with pytest.raises(InvalidIndexError, match=re.escape(str(idx1))):\n idx1.get_loc(idx1)\n\n # get the location of p1/p2 from\n # non-monotonic increasing/decreasing PeriodIndex with duplicate\n idx2 = PeriodIndex([p2, p1, p2])\n expected_idx2_p1 = 1\n expected_idx2_p2 = np.array([True, False, True])\n\n assert idx2.get_loc(p1) == expected_idx2_p1\n assert idx2.get_loc(str(p1)) == expected_idx2_p1\n tm.assert_numpy_array_equal(idx2.get_loc(p2), expected_idx2_p2)\n tm.assert_numpy_array_equal(idx2.get_loc(str(p2)), expected_idx2_p2)\n\n def test_get_loc_integer(self):\n dti = date_range("2016-01-01", periods=3)\n pi = dti.to_period("D")\n with pytest.raises(KeyError, match="16801"):\n pi.get_loc(16801)\n\n pi2 = dti.to_period("Y") # duplicates, ordinals are all 46\n with pytest.raises(KeyError, match="46"):\n pi2.get_loc(46)\n\n def test_get_loc_invalid_string_raises_keyerror(self):\n # GH#34240\n pi = period_range("2000", periods=3, name="A")\n with pytest.raises(KeyError, match="A"):\n pi.get_loc("A")\n\n ser = Series([1, 2, 3], index=pi)\n with pytest.raises(KeyError, match="A"):\n ser.loc["A"]\n\n with pytest.raises(KeyError, match="A"):\n ser["A"]\n\n assert "A" not in ser\n assert "A" not in pi\n\n def test_get_loc_mismatched_freq(self):\n # see also test_get_indexer_mismatched_dtype testing we get analogous\n # behavior for get_loc\n dti = date_range("2016-01-01", periods=3)\n pi = dti.to_period("D")\n pi2 = dti.to_period("W")\n pi3 = pi.view(pi2.dtype) # i.e. matching i8 representations\n\n with pytest.raises(KeyError, match="W-SUN"):\n pi.get_loc(pi2[0])\n\n with pytest.raises(KeyError, match="W-SUN"):\n # even though we have matching i8 values\n pi.get_loc(pi3[0])\n\n\nclass TestGetIndexer:\n def test_get_indexer(self):\n # GH 17717\n p1 = Period("2017-09-01")\n p2 = Period("2017-09-04")\n p3 = Period("2017-09-07")\n\n tp0 = Period("2017-08-31")\n tp1 = Period("2017-09-02")\n tp2 = Period("2017-09-05")\n tp3 = Period("2017-09-09")\n\n idx = PeriodIndex([p1, p2, p3])\n\n tm.assert_numpy_array_equal(\n idx.get_indexer(idx), np.array([0, 1, 2], dtype=np.intp)\n )\n\n target = PeriodIndex([tp0, tp1, tp2, tp3])\n tm.assert_numpy_array_equal(\n idx.get_indexer(target, "pad"), np.array([-1, 0, 1, 2], dtype=np.intp)\n )\n tm.assert_numpy_array_equal(\n idx.get_indexer(target, "backfill"), np.array([0, 1, 2, -1], dtype=np.intp)\n )\n tm.assert_numpy_array_equal(\n idx.get_indexer(target, "nearest"), np.array([0, 0, 1, 2], dtype=np.intp)\n )\n\n res = idx.get_indexer(target, "nearest", tolerance=Timedelta("1 day"))\n tm.assert_numpy_array_equal(res, np.array([0, 0, 1, -1], dtype=np.intp))\n\n def test_get_indexer_mismatched_dtype(self):\n # Check that we return all -1s and do not raise or cast incorrectly\n\n dti = date_range("2016-01-01", periods=3)\n pi = dti.to_period("D")\n pi2 = dti.to_period("W")\n\n expected = np.array([-1, -1, -1], dtype=np.intp)\n\n result = pi.get_indexer(dti)\n tm.assert_numpy_array_equal(result, expected)\n\n # This should work in both directions\n result = dti.get_indexer(pi)\n tm.assert_numpy_array_equal(result, expected)\n\n result = pi.get_indexer(pi2)\n tm.assert_numpy_array_equal(result, expected)\n\n # We expect the same from get_indexer_non_unique\n result = pi.get_indexer_non_unique(dti)[0]\n tm.assert_numpy_array_equal(result, expected)\n\n result = dti.get_indexer_non_unique(pi)[0]\n tm.assert_numpy_array_equal(result, expected)\n\n result = pi.get_indexer_non_unique(pi2)[0]\n tm.assert_numpy_array_equal(result, expected)\n\n def test_get_indexer_mismatched_dtype_different_length(self, non_comparable_idx):\n # without method we aren't checking inequalities, so get all-missing\n # but do not raise\n dti = date_range("2016-01-01", periods=3)\n pi = dti.to_period("D")\n\n other = non_comparable_idx\n\n res = pi[:-1].get_indexer(other)\n expected = -np.ones(other.shape, dtype=np.intp)\n tm.assert_numpy_array_equal(res, expected)\n\n @pytest.mark.parametrize("method", ["pad", "backfill", "nearest"])\n def test_get_indexer_mismatched_dtype_with_method(self, non_comparable_idx, method):\n dti = date_range("2016-01-01", periods=3)\n pi = dti.to_period("D")\n\n other = non_comparable_idx\n\n msg = re.escape(f"Cannot compare dtypes {pi.dtype} and {other.dtype}")\n with pytest.raises(TypeError, match=msg):\n pi.get_indexer(other, method=method)\n\n for dtype in ["object", "category"]:\n other2 = other.astype(dtype)\n if dtype == "object" and isinstance(other, PeriodIndex):\n continue\n # Two different error message patterns depending on dtypes\n msg = "|".join(\n [\n re.escape(msg)\n for msg in (\n f"Cannot compare dtypes {pi.dtype} and {other.dtype}",\n " not supported between instances of ",\n )\n ]\n )\n with pytest.raises(TypeError, match=msg):\n pi.get_indexer(other2, method=method)\n\n def test_get_indexer_non_unique(self):\n # GH 17717\n p1 = Period("2017-09-02")\n p2 = Period("2017-09-03")\n p3 = Period("2017-09-04")\n p4 = Period("2017-09-05")\n\n idx1 = PeriodIndex([p1, p2, p1])\n idx2 = PeriodIndex([p2, p1, p3, p4])\n\n result = idx1.get_indexer_non_unique(idx2)\n expected_indexer = np.array([1, 0, 2, -1, -1], dtype=np.intp)\n expected_missing = np.array([2, 3], dtype=np.intp)\n\n tm.assert_numpy_array_equal(result[0], expected_indexer)\n tm.assert_numpy_array_equal(result[1], expected_missing)\n\n # TODO: This method came from test_period; de-dup with version above\n def test_get_indexer2(self):\n idx = period_range("2000-01-01", periods=3).asfreq("h", how="start")\n tm.assert_numpy_array_equal(\n idx.get_indexer(idx), np.array([0, 1, 2], dtype=np.intp)\n )\n\n target = PeriodIndex(\n ["1999-12-31T23", "2000-01-01T12", "2000-01-02T01"], freq="h"\n )\n tm.assert_numpy_array_equal(\n idx.get_indexer(target, "pad"), np.array([-1, 0, 1], dtype=np.intp)\n )\n tm.assert_numpy_array_equal(\n idx.get_indexer(target, "backfill"), np.array([0, 1, 2], dtype=np.intp)\n )\n tm.assert_numpy_array_equal(\n idx.get_indexer(target, "nearest"), np.array([0, 1, 1], dtype=np.intp)\n )\n tm.assert_numpy_array_equal(\n idx.get_indexer(target, "nearest", tolerance="1 hour"),\n np.array([0, -1, 1], dtype=np.intp),\n )\n\n msg = "Input has different freq=None from PeriodArray\\(freq=h\\)"\n with pytest.raises(ValueError, match=msg):\n idx.get_indexer(target, "nearest", tolerance="1 minute")\n\n tm.assert_numpy_array_equal(\n idx.get_indexer(target, "nearest", tolerance="1 day"),\n np.array([0, 1, 1], dtype=np.intp),\n )\n tol_raw = [\n Timedelta("1 hour"),\n Timedelta("1 hour"),\n np.timedelta64(1, "D"),\n ]\n tm.assert_numpy_array_equal(\n idx.get_indexer(\n target, "nearest", tolerance=[np.timedelta64(x) for x in tol_raw]\n ),\n np.array([0, -1, 1], dtype=np.intp),\n )\n tol_bad = [\n Timedelta("2 hour").to_timedelta64(),\n Timedelta("1 hour").to_timedelta64(),\n np.timedelta64(1, "M"),\n ]\n with pytest.raises(\n libperiod.IncompatibleFrequency, match="Input has different freq=None from"\n ):\n idx.get_indexer(target, "nearest", tolerance=tol_bad)\n\n\nclass TestWhere:\n def test_where(self, listlike_box):\n i = period_range("20130101", periods=5, freq="D")\n cond = [True] * len(i)\n expected = i\n result = i.where(listlike_box(cond))\n tm.assert_index_equal(result, expected)\n\n cond = [False] + [True] * (len(i) - 1)\n expected = PeriodIndex([NaT] + i[1:].tolist(), freq="D")\n result = i.where(listlike_box(cond))\n tm.assert_index_equal(result, expected)\n\n def test_where_other(self):\n i = period_range("20130101", periods=5, freq="D")\n for arr in [np.nan, NaT]:\n result = i.where(notna(i), other=arr)\n expected = i\n tm.assert_index_equal(result, expected)\n\n i2 = i.copy()\n i2 = PeriodIndex([NaT, NaT] + i[2:].tolist(), freq="D")\n result = i.where(notna(i2), i2)\n tm.assert_index_equal(result, i2)\n\n i2 = i.copy()\n i2 = PeriodIndex([NaT, NaT] + i[2:].tolist(), freq="D")\n result = i.where(notna(i2), i2.values)\n tm.assert_index_equal(result, i2)\n\n def test_where_invalid_dtypes(self):\n pi = period_range("20130101", periods=5, freq="D")\n\n tail = pi[2:].tolist()\n i2 = PeriodIndex([NaT, NaT] + tail, freq="D")\n mask = notna(i2)\n\n result = pi.where(mask, i2.asi8)\n expected = pd.Index([NaT._value, NaT._value] + tail, dtype=object)\n assert isinstance(expected[0], int)\n tm.assert_index_equal(result, expected)\n\n tdi = i2.asi8.view("timedelta64[ns]")\n expected = pd.Index([tdi[0], tdi[1]] + tail, dtype=object)\n assert isinstance(expected[0], np.timedelta64)\n result = pi.where(mask, tdi)\n tm.assert_index_equal(result, expected)\n\n dti = i2.to_timestamp("s")\n expected = pd.Index([dti[0], dti[1]] + tail, dtype=object)\n assert expected[0] is NaT\n result = pi.where(mask, dti)\n tm.assert_index_equal(result, expected)\n\n td = Timedelta(days=4)\n expected = pd.Index([td, td] + tail, dtype=object)\n assert expected[0] == td\n result = pi.where(mask, td)\n tm.assert_index_equal(result, expected)\n\n def test_where_mismatched_nat(self):\n pi = period_range("20130101", periods=5, freq="D")\n cond = np.array([True, False, True, True, False])\n\n tdnat = np.timedelta64("NaT", "ns")\n expected = pd.Index([pi[0], tdnat, pi[2], pi[3], tdnat], dtype=object)\n assert expected[1] is tdnat\n result = pi.where(cond, tdnat)\n tm.assert_index_equal(result, expected)\n\n\nclass TestTake:\n def test_take(self):\n # GH#10295\n idx1 = period_range("2011-01-01", "2011-01-31", freq="D", name="idx")\n\n for idx in [idx1]:\n result = idx.take([0])\n assert result == Period("2011-01-01", freq="D")\n\n result = idx.take([5])\n assert result == Period("2011-01-06", freq="D")\n\n result = idx.take([0, 1, 2])\n expected = period_range("2011-01-01", "2011-01-03", freq="D", name="idx")\n tm.assert_index_equal(result, expected)\n assert result.freq == "D"\n assert result.freq == expected.freq\n\n result = idx.take([0, 2, 4])\n expected = PeriodIndex(\n ["2011-01-01", "2011-01-03", "2011-01-05"], freq="D", name="idx"\n )\n tm.assert_index_equal(result, expected)\n assert result.freq == expected.freq\n assert result.freq == "D"\n\n result = idx.take([7, 4, 1])\n expected = PeriodIndex(\n ["2011-01-08", "2011-01-05", "2011-01-02"], freq="D", name="idx"\n )\n tm.assert_index_equal(result, expected)\n assert result.freq == expected.freq\n assert result.freq == "D"\n\n result = idx.take([3, 2, 5])\n expected = PeriodIndex(\n ["2011-01-04", "2011-01-03", "2011-01-06"], freq="D", name="idx"\n )\n tm.assert_index_equal(result, expected)\n assert result.freq == expected.freq\n assert result.freq == "D"\n\n result = idx.take([-3, 2, 5])\n expected = PeriodIndex(\n ["2011-01-29", "2011-01-03", "2011-01-06"], freq="D", name="idx"\n )\n tm.assert_index_equal(result, expected)\n assert result.freq == expected.freq\n assert result.freq == "D"\n\n def test_take_misc(self):\n index = period_range(start="1/1/10", end="12/31/12", freq="D", name="idx")\n expected = PeriodIndex(\n [\n datetime(2010, 1, 6),\n datetime(2010, 1, 7),\n datetime(2010, 1, 9),\n datetime(2010, 1, 13),\n ],\n freq="D",\n name="idx",\n )\n\n taken1 = index.take([5, 6, 8, 12])\n taken2 = index[[5, 6, 8, 12]]\n\n for taken in [taken1, taken2]:\n tm.assert_index_equal(taken, expected)\n assert isinstance(taken, PeriodIndex)\n assert taken.freq == index.freq\n assert taken.name == expected.name\n\n def test_take_fill_value(self):\n # GH#12631\n idx = PeriodIndex(\n ["2011-01-01", "2011-02-01", "2011-03-01"], name="xxx", freq="D"\n )\n result = idx.take(np.array([1, 0, -1]))\n expected = PeriodIndex(\n ["2011-02-01", "2011-01-01", "2011-03-01"], name="xxx", freq="D"\n )\n tm.assert_index_equal(result, expected)\n\n # fill_value\n result = idx.take(np.array([1, 0, -1]), fill_value=True)\n expected = PeriodIndex(\n ["2011-02-01", "2011-01-01", "NaT"], name="xxx", freq="D"\n )\n tm.assert_index_equal(result, expected)\n\n # allow_fill=False\n result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True)\n expected = PeriodIndex(\n ["2011-02-01", "2011-01-01", "2011-03-01"], name="xxx", freq="D"\n )\n tm.assert_index_equal(result, expected)\n\n msg = (\n "When allow_fill=True and fill_value is not None, "\n "all indices must be >= -1"\n )\n with pytest.raises(ValueError, match=msg):\n idx.take(np.array([1, 0, -2]), fill_value=True)\n with pytest.raises(ValueError, match=msg):\n idx.take(np.array([1, 0, -5]), fill_value=True)\n\n msg = "index -5 is out of bounds for( axis 0 with)? size 3"\n with pytest.raises(IndexError, match=msg):\n idx.take(np.array([1, -5]))\n\n\nclass TestGetValue:\n @pytest.mark.parametrize("freq", ["h", "D"])\n def test_get_value_datetime_hourly(self, freq):\n # get_loc and get_value should treat datetime objects symmetrically\n # TODO: this test used to test get_value, which is removed in 2.0.\n # should this test be moved somewhere, or is what's left redundant?\n dti = date_range("2016-01-01", periods=3, freq="MS")\n pi = dti.to_period(freq)\n ser = Series(range(7, 10), index=pi)\n\n ts = dti[0]\n\n assert pi.get_loc(ts) == 0\n assert ser[ts] == 7\n assert ser.loc[ts] == 7\n\n ts2 = ts + Timedelta(hours=3)\n if freq == "h":\n with pytest.raises(KeyError, match="2016-01-01 03:00"):\n pi.get_loc(ts2)\n with pytest.raises(KeyError, match="2016-01-01 03:00"):\n ser[ts2]\n with pytest.raises(KeyError, match="2016-01-01 03:00"):\n ser.loc[ts2]\n else:\n assert pi.get_loc(ts2) == 0\n assert ser[ts2] == 7\n assert ser.loc[ts2] == 7\n\n\nclass TestContains:\n def test_contains(self):\n # GH 17717\n p0 = Period("2017-09-01")\n p1 = Period("2017-09-02")\n p2 = Period("2017-09-03")\n p3 = Period("2017-09-04")\n\n ps0 = [p0, p1, p2]\n idx0 = PeriodIndex(ps0)\n\n for p in ps0:\n assert p in idx0\n assert str(p) in idx0\n\n # GH#31172\n # Higher-resolution period-like are _not_ considered as contained\n key = "2017-09-01 00:00:01"\n assert key not in idx0\n with pytest.raises(KeyError, match=key):\n idx0.get_loc(key)\n\n assert "2017-09" in idx0\n\n assert p3 not in idx0\n\n def test_contains_freq_mismatch(self):\n rng = period_range("2007-01", freq="M", periods=10)\n\n assert Period("2007-01", freq="M") in rng\n assert Period("2007-01", freq="D") not in rng\n assert Period("2007-01", freq="2M") not in rng\n\n def test_contains_nat(self):\n # see gh-13582\n idx = period_range("2007-01", freq="M", periods=10)\n assert NaT not in idx\n assert None not in idx\n assert float("nan") not in idx\n assert np.nan not in idx\n\n idx = PeriodIndex(["2011-01", "NaT", "2011-02"], freq="M")\n assert NaT in idx\n assert None in idx\n assert float("nan") in idx\n assert np.nan in idx\n\n\nclass TestAsOfLocs:\n def test_asof_locs_mismatched_type(self):\n dti = date_range("2016-01-01", periods=3)\n pi = dti.to_period("D")\n pi2 = dti.to_period("h")\n\n mask = np.array([0, 1, 0], dtype=bool)\n\n msg = "must be DatetimeIndex or PeriodIndex"\n with pytest.raises(TypeError, match=msg):\n pi.asof_locs(pd.Index(pi.asi8, dtype=np.int64), mask)\n\n with pytest.raises(TypeError, match=msg):\n pi.asof_locs(pd.Index(pi.asi8, dtype=np.float64), mask)\n\n with pytest.raises(TypeError, match=msg):\n # TimedeltaIndex\n pi.asof_locs(dti - dti, mask)\n\n msg = "Input has different freq=h"\n with pytest.raises(libperiod.IncompatibleFrequency, match=msg):\n pi.asof_locs(pi2, mask)\n | .venv\Lib\site-packages\pandas\tests\indexes\period\test_indexing.py | test_indexing.py | Python | 27,893 | 0.95 | 0.076074 | 0.069382 | react-lib | 38 | 2024-09-15T13:48:53.141789 | BSD-3-Clause | true | 01b52aa723026aa90ac6f4057011c5ee |
import numpy as np\nimport pytest\n\nfrom pandas._libs.tslibs import IncompatibleFrequency\n\nfrom pandas import (\n DataFrame,\n Index,\n PeriodIndex,\n date_range,\n period_range,\n)\nimport pandas._testing as tm\n\n\nclass TestJoin:\n def test_join_outer_indexer(self):\n pi = period_range("1/1/2000", "1/20/2000", freq="D")\n\n result = pi._outer_indexer(pi)\n tm.assert_extension_array_equal(result[0], pi._values)\n tm.assert_numpy_array_equal(result[1], np.arange(len(pi), dtype=np.intp))\n tm.assert_numpy_array_equal(result[2], np.arange(len(pi), dtype=np.intp))\n\n def test_joins(self, join_type):\n index = period_range("1/1/2000", "1/20/2000", freq="D")\n\n joined = index.join(index[:-5], how=join_type)\n\n assert isinstance(joined, PeriodIndex)\n assert joined.freq == index.freq\n\n def test_join_self(self, join_type):\n index = period_range("1/1/2000", "1/20/2000", freq="D")\n\n res = index.join(index, how=join_type)\n assert index is res\n\n def test_join_does_not_recur(self):\n df = DataFrame(\n np.ones((3, 2)),\n index=date_range("2020-01-01", periods=3),\n columns=period_range("2020-01-01", periods=2),\n )\n ser = df.iloc[:2, 0]\n\n res = ser.index.join(df.columns, how="outer")\n expected = Index(\n [ser.index[0], ser.index[1], df.columns[0], df.columns[1]], object\n )\n tm.assert_index_equal(res, expected)\n\n def test_join_mismatched_freq_raises(self):\n index = period_range("1/1/2000", "1/20/2000", freq="D")\n index3 = period_range("1/1/2000", "1/20/2000", freq="2D")\n msg = r".*Input has different freq=2D from Period\(freq=D\)"\n with pytest.raises(IncompatibleFrequency, match=msg):\n index.join(index3)\n | .venv\Lib\site-packages\pandas\tests\indexes\period\test_join.py | test_join.py | Python | 1,835 | 0.85 | 0.103448 | 0 | vue-tools | 487 | 2024-07-23T00:12:43.796519 | GPL-3.0 | true | bffd8961e871252734c2da9b3340a39b |
from pandas import (\n Period,\n PeriodIndex,\n)\n\n\ndef test_is_monotonic_increasing():\n # GH#17717\n p0 = Period("2017-09-01")\n p1 = Period("2017-09-02")\n p2 = Period("2017-09-03")\n\n idx_inc0 = PeriodIndex([p0, p1, p2])\n idx_inc1 = PeriodIndex([p0, p1, p1])\n idx_dec0 = PeriodIndex([p2, p1, p0])\n idx_dec1 = PeriodIndex([p2, p1, p1])\n idx = PeriodIndex([p1, p2, p0])\n\n assert idx_inc0.is_monotonic_increasing is True\n assert idx_inc1.is_monotonic_increasing is True\n assert idx_dec0.is_monotonic_increasing is False\n assert idx_dec1.is_monotonic_increasing is False\n assert idx.is_monotonic_increasing is False\n\n\ndef test_is_monotonic_decreasing():\n # GH#17717\n p0 = Period("2017-09-01")\n p1 = Period("2017-09-02")\n p2 = Period("2017-09-03")\n\n idx_inc0 = PeriodIndex([p0, p1, p2])\n idx_inc1 = PeriodIndex([p0, p1, p1])\n idx_dec0 = PeriodIndex([p2, p1, p0])\n idx_dec1 = PeriodIndex([p2, p1, p1])\n idx = PeriodIndex([p1, p2, p0])\n\n assert idx_inc0.is_monotonic_decreasing is False\n assert idx_inc1.is_monotonic_decreasing is False\n assert idx_dec0.is_monotonic_decreasing is True\n assert idx_dec1.is_monotonic_decreasing is True\n assert idx.is_monotonic_decreasing is False\n | .venv\Lib\site-packages\pandas\tests\indexes\period\test_monotonic.py | test_monotonic.py | Python | 1,258 | 0.95 | 0.047619 | 0.058824 | python-kit | 991 | 2024-12-06T07:53:12.423755 | MIT | true | f1d03aa6080938d7831d2bc78ccd3a6a |
import numpy as np\nimport pytest\n\nfrom pandas import (\n DataFrame,\n PeriodIndex,\n Series,\n date_range,\n period_range,\n)\nimport pandas._testing as tm\n\n\nclass TestPeriodIndex:\n def test_getitem_periodindex_duplicates_string_slice(\n self, using_copy_on_write, warn_copy_on_write\n ):\n # monotonic\n idx = PeriodIndex([2000, 2007, 2007, 2009, 2009], freq="Y-JUN")\n ts = Series(np.random.default_rng(2).standard_normal(len(idx)), index=idx)\n original = ts.copy()\n\n result = ts["2007"]\n expected = ts[1:3]\n tm.assert_series_equal(result, expected)\n with tm.assert_cow_warning(warn_copy_on_write):\n result[:] = 1\n if using_copy_on_write:\n tm.assert_series_equal(ts, original)\n else:\n assert (ts[1:3] == 1).all()\n\n # not monotonic\n idx = PeriodIndex([2000, 2007, 2007, 2009, 2007], freq="Y-JUN")\n ts = Series(np.random.default_rng(2).standard_normal(len(idx)), index=idx)\n\n result = ts["2007"]\n expected = ts[idx == "2007"]\n tm.assert_series_equal(result, expected)\n\n def test_getitem_periodindex_quarter_string(self):\n pi = PeriodIndex(["2Q05", "3Q05", "4Q05", "1Q06", "2Q06"], freq="Q")\n ser = Series(np.random.default_rng(2).random(len(pi)), index=pi).cumsum()\n # Todo: fix these accessors!\n assert ser["05Q4"] == ser.iloc[2]\n\n def test_pindex_slice_index(self):\n pi = period_range(start="1/1/10", end="12/31/12", freq="M")\n s = Series(np.random.default_rng(2).random(len(pi)), index=pi)\n res = s["2010"]\n exp = s[0:12]\n tm.assert_series_equal(res, exp)\n res = s["2011"]\n exp = s[12:24]\n tm.assert_series_equal(res, exp)\n\n @pytest.mark.parametrize("make_range", [date_range, period_range])\n def test_range_slice_day(self, make_range):\n # GH#6716\n idx = make_range(start="2013/01/01", freq="D", periods=400)\n\n msg = "slice indices must be integers or None or have an __index__ method"\n # slices against index should raise IndexError\n values = [\n "2014",\n "2013/02",\n "2013/01/02",\n "2013/02/01 9H",\n "2013/02/01 09:00",\n ]\n for v in values:\n with pytest.raises(TypeError, match=msg):\n idx[v:]\n\n s = Series(np.random.default_rng(2).random(len(idx)), index=idx)\n\n tm.assert_series_equal(s["2013/01/02":], s[1:])\n tm.assert_series_equal(s["2013/01/02":"2013/01/05"], s[1:5])\n tm.assert_series_equal(s["2013/02":], s[31:])\n tm.assert_series_equal(s["2014":], s[365:])\n\n invalid = ["2013/02/01 9H", "2013/02/01 09:00"]\n for v in invalid:\n with pytest.raises(TypeError, match=msg):\n idx[v:]\n\n @pytest.mark.parametrize("make_range", [date_range, period_range])\n def test_range_slice_seconds(self, make_range):\n # GH#6716\n idx = make_range(start="2013/01/01 09:00:00", freq="s", periods=4000)\n msg = "slice indices must be integers or None or have an __index__ method"\n\n # slices against index should raise IndexError\n values = [\n "2014",\n "2013/02",\n "2013/01/02",\n "2013/02/01 9H",\n "2013/02/01 09:00",\n ]\n for v in values:\n with pytest.raises(TypeError, match=msg):\n idx[v:]\n\n s = Series(np.random.default_rng(2).random(len(idx)), index=idx)\n\n tm.assert_series_equal(s["2013/01/01 09:05":"2013/01/01 09:10"], s[300:660])\n tm.assert_series_equal(s["2013/01/01 10:00":"2013/01/01 10:05"], s[3600:3960])\n tm.assert_series_equal(s["2013/01/01 10H":], s[3600:])\n tm.assert_series_equal(s[:"2013/01/01 09:30"], s[:1860])\n for d in ["2013/01/01", "2013/01", "2013"]:\n tm.assert_series_equal(s[d:], s)\n\n @pytest.mark.parametrize("make_range", [date_range, period_range])\n def test_range_slice_outofbounds(self, make_range):\n # GH#5407\n idx = make_range(start="2013/10/01", freq="D", periods=10)\n\n df = DataFrame({"units": [100 + i for i in range(10)]}, index=idx)\n empty = DataFrame(index=idx[:0], columns=["units"])\n empty["units"] = empty["units"].astype("int64")\n\n tm.assert_frame_equal(df["2013/09/01":"2013/09/30"], empty)\n tm.assert_frame_equal(df["2013/09/30":"2013/10/02"], df.iloc[:2])\n tm.assert_frame_equal(df["2013/10/01":"2013/10/02"], df.iloc[:2])\n tm.assert_frame_equal(df["2013/10/02":"2013/09/30"], empty)\n tm.assert_frame_equal(df["2013/10/15":"2013/10/17"], empty)\n tm.assert_frame_equal(df["2013-06":"2013-09"], empty)\n tm.assert_frame_equal(df["2013-11":"2013-12"], empty)\n\n @pytest.mark.parametrize("make_range", [date_range, period_range])\n def test_maybe_cast_slice_bound(self, make_range, frame_or_series):\n idx = make_range(start="2013/10/01", freq="D", periods=10)\n\n obj = DataFrame({"units": [100 + i for i in range(10)]}, index=idx)\n obj = tm.get_obj(obj, frame_or_series)\n\n msg = (\n f"cannot do slice indexing on {type(idx).__name__} with "\n r"these indexers \[foo\] of type str"\n )\n\n # Check the lower-level calls are raising where expected.\n with pytest.raises(TypeError, match=msg):\n idx._maybe_cast_slice_bound("foo", "left")\n with pytest.raises(TypeError, match=msg):\n idx.get_slice_bound("foo", "left")\n\n with pytest.raises(TypeError, match=msg):\n obj["2013/09/30":"foo"]\n with pytest.raises(TypeError, match=msg):\n obj["foo":"2013/09/30"]\n with pytest.raises(TypeError, match=msg):\n obj.loc["2013/09/30":"foo"]\n with pytest.raises(TypeError, match=msg):\n obj.loc["foo":"2013/09/30"]\n\n def test_partial_slice_doesnt_require_monotonicity(self):\n # See also: DatetimeIndex test ofm the same name\n dti = date_range("2014-01-01", periods=30, freq="30D")\n pi = dti.to_period("D")\n\n ser_montonic = Series(np.arange(30), index=pi)\n\n shuffler = list(range(0, 30, 2)) + list(range(1, 31, 2))\n ser = ser_montonic.iloc[shuffler]\n nidx = ser.index\n\n # Manually identified locations of year==2014\n indexer_2014 = np.array(\n [0, 1, 2, 3, 4, 5, 6, 15, 16, 17, 18, 19, 20], dtype=np.intp\n )\n assert (nidx[indexer_2014].year == 2014).all()\n assert not (nidx[~indexer_2014].year == 2014).any()\n\n result = nidx.get_loc("2014")\n tm.assert_numpy_array_equal(result, indexer_2014)\n\n expected = ser.iloc[indexer_2014]\n result = ser.loc["2014"]\n tm.assert_series_equal(result, expected)\n\n result = ser["2014"]\n tm.assert_series_equal(result, expected)\n\n # Manually identified locations where ser.index is within Mat 2015\n indexer_may2015 = np.array([23], dtype=np.intp)\n assert nidx[23].year == 2015 and nidx[23].month == 5\n\n result = nidx.get_loc("May 2015")\n tm.assert_numpy_array_equal(result, indexer_may2015)\n\n expected = ser.iloc[indexer_may2015]\n result = ser.loc["May 2015"]\n tm.assert_series_equal(result, expected)\n\n result = ser["May 2015"]\n tm.assert_series_equal(result, expected)\n | .venv\Lib\site-packages\pandas\tests\indexes\period\test_partial_slicing.py | test_partial_slicing.py | Python | 7,433 | 0.95 | 0.080808 | 0.074074 | node-utils | 807 | 2023-08-29T14:07:03.423214 | MIT | true | 295b26e07cec1aae308f58aa88054f3d |
import numpy as np\nimport pytest\n\nfrom pandas import (\n Index,\n NaT,\n Period,\n PeriodIndex,\n Series,\n date_range,\n offsets,\n period_range,\n)\nimport pandas._testing as tm\n\n\nclass TestPeriodIndex:\n def test_view_asi8(self):\n idx = PeriodIndex([], freq="M")\n\n exp = np.array([], dtype=np.int64)\n tm.assert_numpy_array_equal(idx.view("i8"), exp)\n tm.assert_numpy_array_equal(idx.asi8, exp)\n\n idx = PeriodIndex(["2011-01", NaT], freq="M")\n\n exp = np.array([492, -9223372036854775808], dtype=np.int64)\n tm.assert_numpy_array_equal(idx.view("i8"), exp)\n tm.assert_numpy_array_equal(idx.asi8, exp)\n\n exp = np.array([14975, -9223372036854775808], dtype=np.int64)\n idx = PeriodIndex(["2011-01-01", NaT], freq="D")\n tm.assert_numpy_array_equal(idx.view("i8"), exp)\n tm.assert_numpy_array_equal(idx.asi8, exp)\n\n def test_values(self):\n idx = PeriodIndex([], freq="M")\n\n exp = np.array([], dtype=object)\n tm.assert_numpy_array_equal(idx.values, exp)\n tm.assert_numpy_array_equal(idx.to_numpy(), exp)\n\n exp = np.array([], dtype=np.int64)\n tm.assert_numpy_array_equal(idx.asi8, exp)\n\n idx = PeriodIndex(["2011-01", NaT], freq="M")\n\n exp = np.array([Period("2011-01", freq="M"), NaT], dtype=object)\n tm.assert_numpy_array_equal(idx.values, exp)\n tm.assert_numpy_array_equal(idx.to_numpy(), exp)\n exp = np.array([492, -9223372036854775808], dtype=np.int64)\n tm.assert_numpy_array_equal(idx.asi8, exp)\n\n idx = PeriodIndex(["2011-01-01", NaT], freq="D")\n\n exp = np.array([Period("2011-01-01", freq="D"), NaT], dtype=object)\n tm.assert_numpy_array_equal(idx.values, exp)\n tm.assert_numpy_array_equal(idx.to_numpy(), exp)\n exp = np.array([14975, -9223372036854775808], dtype=np.int64)\n tm.assert_numpy_array_equal(idx.asi8, exp)\n\n @pytest.mark.parametrize(\n "field",\n [\n "year",\n "month",\n "day",\n "hour",\n "minute",\n "second",\n "weekofyear",\n "week",\n "dayofweek",\n "day_of_week",\n "dayofyear",\n "day_of_year",\n "quarter",\n "qyear",\n "days_in_month",\n ],\n )\n @pytest.mark.parametrize(\n "periodindex",\n [\n period_range(freq="Y", start="1/1/2001", end="12/1/2005"),\n period_range(freq="Q", start="1/1/2001", end="12/1/2002"),\n period_range(freq="M", start="1/1/2001", end="1/1/2002"),\n period_range(freq="D", start="12/1/2001", end="6/1/2001"),\n period_range(freq="h", start="12/31/2001", end="1/1/2002 23:00"),\n period_range(freq="Min", start="12/31/2001", end="1/1/2002 00:20"),\n period_range(\n freq="s", start="12/31/2001 00:00:00", end="12/31/2001 00:05:00"\n ),\n period_range(end=Period("2006-12-31", "W"), periods=10),\n ],\n )\n def test_fields(self, periodindex, field):\n periods = list(periodindex)\n ser = Series(periodindex)\n\n field_idx = getattr(periodindex, field)\n assert len(periodindex) == len(field_idx)\n for x, val in zip(periods, field_idx):\n assert getattr(x, field) == val\n\n if len(ser) == 0:\n return\n\n field_s = getattr(ser.dt, field)\n assert len(periodindex) == len(field_s)\n for x, val in zip(periods, field_s):\n assert getattr(x, field) == val\n\n def test_is_(self):\n create_index = lambda: period_range(freq="Y", start="1/1/2001", end="12/1/2009")\n index = create_index()\n assert index.is_(index)\n assert not index.is_(create_index())\n assert index.is_(index.view())\n assert index.is_(index.view().view().view().view().view())\n assert index.view().is_(index)\n ind2 = index.view()\n index.name = "Apple"\n assert ind2.is_(index)\n assert not index.is_(index[:])\n assert not index.is_(index.asfreq("M"))\n assert not index.is_(index.asfreq("Y"))\n\n assert not index.is_(index - 2)\n assert not index.is_(index - 0)\n\n def test_index_unique(self):\n idx = PeriodIndex([2000, 2007, 2007, 2009, 2009], freq="Y-JUN")\n expected = PeriodIndex([2000, 2007, 2009], freq="Y-JUN")\n tm.assert_index_equal(idx.unique(), expected)\n assert idx.nunique() == 3\n\n def test_pindex_fieldaccessor_nat(self):\n idx = PeriodIndex(\n ["2011-01", "2011-02", "NaT", "2012-03", "2012-04"], freq="D", name="name"\n )\n\n exp = Index([2011, 2011, -1, 2012, 2012], dtype=np.int64, name="name")\n tm.assert_index_equal(idx.year, exp)\n exp = Index([1, 2, -1, 3, 4], dtype=np.int64, name="name")\n tm.assert_index_equal(idx.month, exp)\n\n def test_pindex_multiples(self):\n expected = PeriodIndex(\n ["2011-01", "2011-03", "2011-05", "2011-07", "2011-09", "2011-11"],\n freq="2M",\n )\n\n pi = period_range(start="1/1/11", end="12/31/11", freq="2M")\n tm.assert_index_equal(pi, expected)\n assert pi.freq == offsets.MonthEnd(2)\n assert pi.freqstr == "2M"\n\n pi = period_range(start="1/1/11", periods=6, freq="2M")\n tm.assert_index_equal(pi, expected)\n assert pi.freq == offsets.MonthEnd(2)\n assert pi.freqstr == "2M"\n\n @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")\n @pytest.mark.filterwarnings("ignore:Period with BDay freq:FutureWarning")\n def test_iteration(self):\n index = period_range(start="1/1/10", periods=4, freq="B")\n\n result = list(index)\n assert isinstance(result[0], Period)\n assert result[0].freq == index.freq\n\n def test_with_multi_index(self):\n # #1705\n index = date_range("1/1/2012", periods=4, freq="12h")\n index_as_arrays = [index.to_period(freq="D"), index.hour]\n\n s = Series([0, 1, 2, 3], index_as_arrays)\n\n assert isinstance(s.index.levels[0], PeriodIndex)\n\n assert isinstance(s.index.values[0][0], Period)\n\n def test_map(self):\n # test_map_dictlike generally tests\n\n index = PeriodIndex([2005, 2007, 2009], freq="Y")\n result = index.map(lambda x: x.ordinal)\n exp = Index([x.ordinal for x in index])\n tm.assert_index_equal(result, exp)\n\n\ndef test_maybe_convert_timedelta():\n pi = PeriodIndex(["2000", "2001"], freq="D")\n offset = offsets.Day(2)\n assert pi._maybe_convert_timedelta(offset) == 2\n assert pi._maybe_convert_timedelta(2) == 2\n\n offset = offsets.BusinessDay()\n msg = r"Input has different freq=B from PeriodIndex\(freq=D\)"\n with pytest.raises(ValueError, match=msg):\n pi._maybe_convert_timedelta(offset)\n\n\n@pytest.mark.parametrize("array", [True, False])\ndef test_dunder_array(array):\n obj = PeriodIndex(["2000-01-01", "2001-01-01"], freq="D")\n if array:\n obj = obj._data\n\n expected = np.array([obj[0], obj[1]], dtype=object)\n result = np.array(obj)\n tm.assert_numpy_array_equal(result, expected)\n\n result = np.asarray(obj)\n tm.assert_numpy_array_equal(result, expected)\n\n expected = obj.asi8\n for dtype in ["i8", "int64", np.int64]:\n result = np.array(obj, dtype=dtype)\n tm.assert_numpy_array_equal(result, expected)\n\n result = np.asarray(obj, dtype=dtype)\n tm.assert_numpy_array_equal(result, expected)\n\n for dtype in ["float64", "int32", "uint64"]:\n msg = "argument must be"\n with pytest.raises(TypeError, match=msg):\n np.array(obj, dtype=dtype)\n with pytest.raises(TypeError, match=msg):\n np.array(obj, dtype=getattr(np, dtype))\n | .venv\Lib\site-packages\pandas\tests\indexes\period\test_period.py | test_period.py | Python | 7,861 | 0.95 | 0.08658 | 0.010695 | vue-tools | 459 | 2024-12-14T23:53:47.613034 | BSD-3-Clause | true | 79a4ad699e2a190a3015faf5ecb794dd |
import numpy as np\nimport pytest\n\nfrom pandas import (\n NaT,\n Period,\n PeriodIndex,\n date_range,\n period_range,\n)\nimport pandas._testing as tm\n\n\nclass TestPeriodRangeKeywords:\n def test_required_arguments(self):\n msg = (\n "Of the three parameters: start, end, and periods, exactly two "\n "must be specified"\n )\n with pytest.raises(ValueError, match=msg):\n period_range("2011-1-1", "2012-1-1", "B")\n\n def test_required_arguments2(self):\n start = Period("02-Apr-2005", "D")\n msg = (\n "Of the three parameters: start, end, and periods, exactly two "\n "must be specified"\n )\n with pytest.raises(ValueError, match=msg):\n period_range(start=start)\n\n def test_required_arguments3(self):\n # not enough params\n msg = (\n "Of the three parameters: start, end, and periods, "\n "exactly two must be specified"\n )\n with pytest.raises(ValueError, match=msg):\n period_range(start="2017Q1")\n\n with pytest.raises(ValueError, match=msg):\n period_range(end="2017Q1")\n\n with pytest.raises(ValueError, match=msg):\n period_range(periods=5)\n\n with pytest.raises(ValueError, match=msg):\n period_range()\n\n def test_required_arguments_too_many(self):\n msg = (\n "Of the three parameters: start, end, and periods, "\n "exactly two must be specified"\n )\n with pytest.raises(ValueError, match=msg):\n period_range(start="2017Q1", end="2018Q1", periods=8, freq="Q")\n\n def test_start_end_non_nat(self):\n # start/end NaT\n msg = "start and end must not be NaT"\n with pytest.raises(ValueError, match=msg):\n period_range(start=NaT, end="2018Q1")\n with pytest.raises(ValueError, match=msg):\n period_range(start=NaT, end="2018Q1", freq="Q")\n\n with pytest.raises(ValueError, match=msg):\n period_range(start="2017Q1", end=NaT)\n with pytest.raises(ValueError, match=msg):\n period_range(start="2017Q1", end=NaT, freq="Q")\n\n def test_periods_requires_integer(self):\n # invalid periods param\n msg = "periods must be a number, got foo"\n with pytest.raises(TypeError, match=msg):\n period_range(start="2017Q1", periods="foo")\n\n\nclass TestPeriodRange:\n @pytest.mark.parametrize(\n "freq_offset, freq_period",\n [\n ("D", "D"),\n ("W", "W"),\n ("QE", "Q"),\n ("YE", "Y"),\n ],\n )\n def test_construction_from_string(self, freq_offset, freq_period):\n # non-empty\n expected = date_range(\n start="2017-01-01", periods=5, freq=freq_offset, name="foo"\n ).to_period()\n start, end = str(expected[0]), str(expected[-1])\n\n result = period_range(start=start, end=end, freq=freq_period, name="foo")\n tm.assert_index_equal(result, expected)\n\n result = period_range(start=start, periods=5, freq=freq_period, name="foo")\n tm.assert_index_equal(result, expected)\n\n result = period_range(end=end, periods=5, freq=freq_period, name="foo")\n tm.assert_index_equal(result, expected)\n\n # empty\n expected = PeriodIndex([], freq=freq_period, name="foo")\n\n result = period_range(start=start, periods=0, freq=freq_period, name="foo")\n tm.assert_index_equal(result, expected)\n\n result = period_range(end=end, periods=0, freq=freq_period, name="foo")\n tm.assert_index_equal(result, expected)\n\n result = period_range(start=end, end=start, freq=freq_period, name="foo")\n tm.assert_index_equal(result, expected)\n\n def test_construction_from_string_monthly(self):\n # non-empty\n expected = date_range(\n start="2017-01-01", periods=5, freq="ME", name="foo"\n ).to_period()\n start, end = str(expected[0]), str(expected[-1])\n\n result = period_range(start=start, end=end, freq="M", name="foo")\n tm.assert_index_equal(result, expected)\n\n result = period_range(start=start, periods=5, freq="M", name="foo")\n tm.assert_index_equal(result, expected)\n\n result = period_range(end=end, periods=5, freq="M", name="foo")\n tm.assert_index_equal(result, expected)\n\n # empty\n expected = PeriodIndex([], freq="M", name="foo")\n\n result = period_range(start=start, periods=0, freq="M", name="foo")\n tm.assert_index_equal(result, expected)\n\n result = period_range(end=end, periods=0, freq="M", name="foo")\n tm.assert_index_equal(result, expected)\n\n result = period_range(start=end, end=start, freq="M", name="foo")\n tm.assert_index_equal(result, expected)\n\n def test_construction_from_period(self):\n # upsampling\n start, end = Period("2017Q1", freq="Q"), Period("2018Q1", freq="Q")\n expected = date_range(\n start="2017-03-31", end="2018-03-31", freq="ME", name="foo"\n ).to_period()\n result = period_range(start=start, end=end, freq="M", name="foo")\n tm.assert_index_equal(result, expected)\n\n # downsampling\n start = Period("2017-1", freq="M")\n end = Period("2019-12", freq="M")\n expected = date_range(\n start="2017-01-31", end="2019-12-31", freq="QE", name="foo"\n ).to_period()\n result = period_range(start=start, end=end, freq="Q", name="foo")\n tm.assert_index_equal(result, expected)\n\n # test for issue # 21793\n start = Period("2017Q1", freq="Q")\n end = Period("2018Q1", freq="Q")\n idx = period_range(start=start, end=end, freq="Q", name="foo")\n result = idx == idx.values\n expected = np.array([True, True, True, True, True])\n tm.assert_numpy_array_equal(result, expected)\n\n # empty\n expected = PeriodIndex([], freq="W", name="foo")\n\n result = period_range(start=start, periods=0, freq="W", name="foo")\n tm.assert_index_equal(result, expected)\n\n result = period_range(end=end, periods=0, freq="W", name="foo")\n tm.assert_index_equal(result, expected)\n\n result = period_range(start=end, end=start, freq="W", name="foo")\n tm.assert_index_equal(result, expected)\n\n def test_mismatched_start_end_freq_raises(self):\n depr_msg = "Period with BDay freq is deprecated"\n msg = "'w' is deprecated and will be removed in a future version."\n with tm.assert_produces_warning(FutureWarning, match=msg):\n end_w = Period("2006-12-31", "1w")\n\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n start_b = Period("02-Apr-2005", "B")\n end_b = Period("2005-05-01", "B")\n\n msg = "start and end must have same freq"\n with pytest.raises(ValueError, match=msg):\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n period_range(start=start_b, end=end_w)\n\n # without mismatch we are OK\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n period_range(start=start_b, end=end_b)\n\n\nclass TestPeriodRangeDisallowedFreqs:\n def test_constructor_U(self):\n # U was used as undefined period\n with pytest.raises(ValueError, match="Invalid frequency: X"):\n period_range("2007-1-1", periods=500, freq="X")\n\n @pytest.mark.parametrize(\n "freq,freq_depr",\n [\n ("2Y", "2A"),\n ("2Y", "2a"),\n ("2Y-AUG", "2A-AUG"),\n ("2Y-AUG", "2A-aug"),\n ],\n )\n def test_a_deprecated_from_time_series(self, freq, freq_depr):\n # GH#52536\n msg = f"'{freq_depr[1:]}' is deprecated and will be removed in a "\n f"future version. Please use '{freq[1:]}' instead."\n\n with tm.assert_produces_warning(FutureWarning, match=msg):\n period_range(freq=freq_depr, start="1/1/2001", end="12/1/2009")\n\n @pytest.mark.parametrize("freq_depr", ["2H", "2MIN", "2S", "2US", "2NS"])\n def test_uppercase_freq_deprecated_from_time_series(self, freq_depr):\n # GH#52536, GH#54939\n msg = f"'{freq_depr[1:]}' is deprecated and will be removed in a "\n f"future version. Please use '{freq_depr.lower()[1:]}' instead."\n\n with tm.assert_produces_warning(FutureWarning, match=msg):\n period_range("2020-01-01 00:00:00 00:00", periods=2, freq=freq_depr)\n\n @pytest.mark.parametrize("freq_depr", ["2m", "2q-sep", "2y", "2w"])\n def test_lowercase_freq_deprecated_from_time_series(self, freq_depr):\n # GH#52536, GH#54939\n msg = f"'{freq_depr[1:]}' is deprecated and will be removed in a "\n f"future version. Please use '{freq_depr.upper()[1:]}' instead."\n\n with tm.assert_produces_warning(FutureWarning, match=msg):\n period_range(freq=freq_depr, start="1/1/2001", end="12/1/2009")\n | .venv\Lib\site-packages\pandas\tests\indexes\period\test_period_range.py | test_period_range.py | Python | 8,979 | 0.95 | 0.074689 | 0.082902 | react-lib | 155 | 2023-07-14T22:11:45.936061 | BSD-3-Clause | true | d2e10b72090b181a16a11bf350bf3d97 |
import numpy as np\nimport pytest\n\nfrom pandas import (\n NaT,\n PeriodIndex,\n period_range,\n)\nimport pandas._testing as tm\n\nfrom pandas.tseries import offsets\n\n\nclass TestPickle:\n @pytest.mark.parametrize("freq", ["D", "M", "Y"])\n def test_pickle_round_trip(self, freq):\n idx = PeriodIndex(["2016-05-16", "NaT", NaT, np.nan], freq=freq)\n result = tm.round_trip_pickle(idx)\n tm.assert_index_equal(result, idx)\n\n def test_pickle_freq(self):\n # GH#2891\n prng = period_range("1/1/2011", "1/1/2012", freq="M")\n new_prng = tm.round_trip_pickle(prng)\n assert new_prng.freq == offsets.MonthEnd()\n assert new_prng.freqstr == "M"\n | .venv\Lib\site-packages\pandas\tests\indexes\period\test_pickle.py | test_pickle.py | Python | 692 | 0.95 | 0.115385 | 0.047619 | vue-tools | 324 | 2024-11-07T00:08:21.849869 | GPL-3.0 | true | 0e356476d9b1cdfbaaaf6e8fe4082541 |
import pytest\n\nimport pandas as pd\n\n\nclass TestResolution:\n @pytest.mark.parametrize(\n "freq,expected",\n [\n ("Y", "year"),\n ("Q", "quarter"),\n ("M", "month"),\n ("D", "day"),\n ("h", "hour"),\n ("min", "minute"),\n ("s", "second"),\n ("ms", "millisecond"),\n ("us", "microsecond"),\n ],\n )\n def test_resolution(self, freq, expected):\n idx = pd.period_range(start="2013-04-01", periods=30, freq=freq)\n assert idx.resolution == expected\n | .venv\Lib\site-packages\pandas\tests\indexes\period\test_resolution.py | test_resolution.py | Python | 571 | 0.85 | 0.086957 | 0 | node-utils | 913 | 2023-11-24T06:04:08.878576 | Apache-2.0 | true | c2ce49ee7deef99f09e6eeda3ceeb6d7 |
"""Tests for PeriodIndex behaving like a vectorized Period scalar"""\n\nimport pytest\n\nfrom pandas import (\n Timedelta,\n date_range,\n period_range,\n)\nimport pandas._testing as tm\n\n\nclass TestPeriodIndexOps:\n def test_start_time(self):\n # GH#17157\n index = period_range(freq="M", start="2016-01-01", end="2016-05-31")\n expected_index = date_range("2016-01-01", end="2016-05-31", freq="MS")\n tm.assert_index_equal(index.start_time, expected_index)\n\n def test_end_time(self):\n # GH#17157\n index = period_range(freq="M", start="2016-01-01", end="2016-05-31")\n expected_index = date_range("2016-01-01", end="2016-05-31", freq="ME")\n expected_index += Timedelta(1, "D") - Timedelta(1, "ns")\n tm.assert_index_equal(index.end_time, expected_index)\n\n @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")\n @pytest.mark.filterwarnings(\n "ignore:Period with BDay freq is deprecated:FutureWarning"\n )\n def test_end_time_business_friday(self):\n # GH#34449\n pi = period_range("1990-01-05", freq="B", periods=1)\n result = pi.end_time\n\n dti = date_range("1990-01-05", freq="D", periods=1)._with_freq(None)\n expected = dti + Timedelta(days=1, nanoseconds=-1)\n tm.assert_index_equal(result, expected)\n | .venv\Lib\site-packages\pandas\tests\indexes\period\test_scalar_compat.py | test_scalar_compat.py | Python | 1,350 | 0.95 | 0.131579 | 0.096774 | awesome-app | 301 | 2024-01-13T13:22:21.215787 | GPL-3.0 | true | aa245aedf32c6b6c09b6e2fa7fd2464a |
import numpy as np\nimport pytest\n\nfrom pandas._libs.tslibs import IncompatibleFrequency\n\nfrom pandas import (\n NaT,\n Period,\n PeriodIndex,\n)\nimport pandas._testing as tm\n\n\nclass TestSearchsorted:\n @pytest.mark.parametrize("freq", ["D", "2D"])\n def test_searchsorted(self, freq):\n pidx = PeriodIndex(\n ["2014-01-01", "2014-01-02", "2014-01-03", "2014-01-04", "2014-01-05"],\n freq=freq,\n )\n\n p1 = Period("2014-01-01", freq=freq)\n assert pidx.searchsorted(p1) == 0\n\n p2 = Period("2014-01-04", freq=freq)\n assert pidx.searchsorted(p2) == 3\n\n assert pidx.searchsorted(NaT) == 5\n\n msg = "Input has different freq=h from PeriodArray"\n with pytest.raises(IncompatibleFrequency, match=msg):\n pidx.searchsorted(Period("2014-01-01", freq="h"))\n\n msg = "Input has different freq=5D from PeriodArray"\n with pytest.raises(IncompatibleFrequency, match=msg):\n pidx.searchsorted(Period("2014-01-01", freq="5D"))\n\n def test_searchsorted_different_argument_classes(self, listlike_box):\n pidx = PeriodIndex(\n ["2014-01-01", "2014-01-02", "2014-01-03", "2014-01-04", "2014-01-05"],\n freq="D",\n )\n result = pidx.searchsorted(listlike_box(pidx))\n expected = np.arange(len(pidx), dtype=result.dtype)\n tm.assert_numpy_array_equal(result, expected)\n\n result = pidx._data.searchsorted(listlike_box(pidx))\n tm.assert_numpy_array_equal(result, expected)\n\n def test_searchsorted_invalid(self):\n pidx = PeriodIndex(\n ["2014-01-01", "2014-01-02", "2014-01-03", "2014-01-04", "2014-01-05"],\n freq="D",\n )\n\n other = np.array([0, 1], dtype=np.int64)\n\n msg = "|".join(\n [\n "searchsorted requires compatible dtype or scalar",\n "value should be a 'Period', 'NaT', or array of those. Got",\n ]\n )\n with pytest.raises(TypeError, match=msg):\n pidx.searchsorted(other)\n\n with pytest.raises(TypeError, match=msg):\n pidx.searchsorted(other.astype("timedelta64[ns]"))\n\n with pytest.raises(TypeError, match=msg):\n pidx.searchsorted(np.timedelta64(4))\n\n with pytest.raises(TypeError, match=msg):\n pidx.searchsorted(np.timedelta64("NaT", "ms"))\n\n with pytest.raises(TypeError, match=msg):\n pidx.searchsorted(np.datetime64(4, "ns"))\n\n with pytest.raises(TypeError, match=msg):\n pidx.searchsorted(np.datetime64("NaT", "ns"))\n | .venv\Lib\site-packages\pandas\tests\indexes\period\test_searchsorted.py | test_searchsorted.py | Python | 2,604 | 0.85 | 0.05 | 0 | awesome-app | 511 | 2023-11-15T01:24:13.187629 | GPL-3.0 | true | 970151aa039a4bd585ffef9cf7ccaa61 |
import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n PeriodIndex,\n date_range,\n period_range,\n)\nimport pandas._testing as tm\n\n\ndef _permute(obj):\n return obj.take(np.random.default_rng(2).permutation(len(obj)))\n\n\nclass TestPeriodIndex:\n def test_union(self, sort):\n # union\n other1 = period_range("1/1/2000", freq="D", periods=5)\n rng1 = period_range("1/6/2000", freq="D", periods=5)\n expected1 = PeriodIndex(\n [\n "2000-01-06",\n "2000-01-07",\n "2000-01-08",\n "2000-01-09",\n "2000-01-10",\n "2000-01-01",\n "2000-01-02",\n "2000-01-03",\n "2000-01-04",\n "2000-01-05",\n ],\n freq="D",\n )\n\n rng2 = period_range("1/1/2000", freq="D", periods=5)\n other2 = period_range("1/4/2000", freq="D", periods=5)\n expected2 = period_range("1/1/2000", freq="D", periods=8)\n\n rng3 = period_range("1/1/2000", freq="D", periods=5)\n other3 = PeriodIndex([], freq="D")\n expected3 = period_range("1/1/2000", freq="D", periods=5)\n\n rng4 = period_range("2000-01-01 09:00", freq="h", periods=5)\n other4 = period_range("2000-01-02 09:00", freq="h", periods=5)\n expected4 = PeriodIndex(\n [\n "2000-01-01 09:00",\n "2000-01-01 10:00",\n "2000-01-01 11:00",\n "2000-01-01 12:00",\n "2000-01-01 13:00",\n "2000-01-02 09:00",\n "2000-01-02 10:00",\n "2000-01-02 11:00",\n "2000-01-02 12:00",\n "2000-01-02 13:00",\n ],\n freq="h",\n )\n\n rng5 = PeriodIndex(\n ["2000-01-01 09:01", "2000-01-01 09:03", "2000-01-01 09:05"], freq="min"\n )\n other5 = PeriodIndex(\n ["2000-01-01 09:01", "2000-01-01 09:05", "2000-01-01 09:08"], freq="min"\n )\n expected5 = PeriodIndex(\n [\n "2000-01-01 09:01",\n "2000-01-01 09:03",\n "2000-01-01 09:05",\n "2000-01-01 09:08",\n ],\n freq="min",\n )\n\n rng6 = period_range("2000-01-01", freq="M", periods=7)\n other6 = period_range("2000-04-01", freq="M", periods=7)\n expected6 = period_range("2000-01-01", freq="M", periods=10)\n\n rng7 = period_range("2003-01-01", freq="Y", periods=5)\n other7 = period_range("1998-01-01", freq="Y", periods=8)\n expected7 = PeriodIndex(\n [\n "2003",\n "2004",\n "2005",\n "2006",\n "2007",\n "1998",\n "1999",\n "2000",\n "2001",\n "2002",\n ],\n freq="Y",\n )\n\n rng8 = PeriodIndex(\n ["1/3/2000", "1/2/2000", "1/1/2000", "1/5/2000", "1/4/2000"], freq="D"\n )\n other8 = period_range("1/6/2000", freq="D", periods=5)\n expected8 = PeriodIndex(\n [\n "1/3/2000",\n "1/2/2000",\n "1/1/2000",\n "1/5/2000",\n "1/4/2000",\n "1/6/2000",\n "1/7/2000",\n "1/8/2000",\n "1/9/2000",\n "1/10/2000",\n ],\n freq="D",\n )\n\n for rng, other, expected in [\n (rng1, other1, expected1),\n (rng2, other2, expected2),\n (rng3, other3, expected3),\n (rng4, other4, expected4),\n (rng5, other5, expected5),\n (rng6, other6, expected6),\n (rng7, other7, expected7),\n (rng8, other8, expected8),\n ]:\n result_union = rng.union(other, sort=sort)\n if sort is None:\n expected = expected.sort_values()\n tm.assert_index_equal(result_union, expected)\n\n def test_union_misc(self, sort):\n index = period_range("1/1/2000", "1/20/2000", freq="D")\n\n result = index[:-5].union(index[10:], sort=sort)\n tm.assert_index_equal(result, index)\n\n # not in order\n result = _permute(index[:-5]).union(_permute(index[10:]), sort=sort)\n if sort is False:\n tm.assert_index_equal(result.sort_values(), index)\n else:\n tm.assert_index_equal(result, index)\n\n # cast if different frequencies\n index = period_range("1/1/2000", "1/20/2000", freq="D")\n index2 = period_range("1/1/2000", "1/20/2000", freq="W-WED")\n result = index.union(index2, sort=sort)\n expected = index.astype(object).union(index2.astype(object), sort=sort)\n tm.assert_index_equal(result, expected)\n\n def test_intersection(self, sort):\n index = period_range("1/1/2000", "1/20/2000", freq="D")\n\n result = index[:-5].intersection(index[10:], sort=sort)\n tm.assert_index_equal(result, index[10:-5])\n\n # not in order\n left = _permute(index[:-5])\n right = _permute(index[10:])\n result = left.intersection(right, sort=sort)\n if sort is False:\n tm.assert_index_equal(result.sort_values(), index[10:-5])\n else:\n tm.assert_index_equal(result, index[10:-5])\n\n # cast if different frequencies\n index = period_range("1/1/2000", "1/20/2000", freq="D")\n index2 = period_range("1/1/2000", "1/20/2000", freq="W-WED")\n\n result = index.intersection(index2, sort=sort)\n expected = pd.Index([], dtype=object)\n tm.assert_index_equal(result, expected)\n\n index3 = period_range("1/1/2000", "1/20/2000", freq="2D")\n result = index.intersection(index3, sort=sort)\n tm.assert_index_equal(result, expected)\n\n def test_intersection_cases(self, sort):\n base = period_range("6/1/2000", "6/30/2000", freq="D", name="idx")\n\n # if target has the same name, it is preserved\n rng2 = period_range("5/15/2000", "6/20/2000", freq="D", name="idx")\n expected2 = period_range("6/1/2000", "6/20/2000", freq="D", name="idx")\n\n # if target name is different, it will be reset\n rng3 = period_range("5/15/2000", "6/20/2000", freq="D", name="other")\n expected3 = period_range("6/1/2000", "6/20/2000", freq="D", name=None)\n\n rng4 = period_range("7/1/2000", "7/31/2000", freq="D", name="idx")\n expected4 = PeriodIndex([], name="idx", freq="D")\n\n for rng, expected in [\n (rng2, expected2),\n (rng3, expected3),\n (rng4, expected4),\n ]:\n result = base.intersection(rng, sort=sort)\n tm.assert_index_equal(result, expected)\n assert result.name == expected.name\n assert result.freq == expected.freq\n\n # non-monotonic\n base = PeriodIndex(\n ["2011-01-05", "2011-01-04", "2011-01-02", "2011-01-03"],\n freq="D",\n name="idx",\n )\n\n rng2 = PeriodIndex(\n ["2011-01-04", "2011-01-02", "2011-02-02", "2011-02-03"],\n freq="D",\n name="idx",\n )\n expected2 = PeriodIndex(["2011-01-04", "2011-01-02"], freq="D", name="idx")\n\n rng3 = PeriodIndex(\n ["2011-01-04", "2011-01-02", "2011-02-02", "2011-02-03"],\n freq="D",\n name="other",\n )\n expected3 = PeriodIndex(["2011-01-04", "2011-01-02"], freq="D", name=None)\n\n rng4 = period_range("7/1/2000", "7/31/2000", freq="D", name="idx")\n expected4 = PeriodIndex([], freq="D", name="idx")\n\n for rng, expected in [\n (rng2, expected2),\n (rng3, expected3),\n (rng4, expected4),\n ]:\n result = base.intersection(rng, sort=sort)\n if sort is None:\n expected = expected.sort_values()\n tm.assert_index_equal(result, expected)\n assert result.name == expected.name\n assert result.freq == "D"\n\n # empty same freq\n rng = date_range("6/1/2000", "6/15/2000", freq="min")\n result = rng[0:0].intersection(rng)\n assert len(result) == 0\n\n result = rng.intersection(rng[0:0])\n assert len(result) == 0\n\n def test_difference(self, sort):\n # diff\n period_rng = ["1/3/2000", "1/2/2000", "1/1/2000", "1/5/2000", "1/4/2000"]\n rng1 = PeriodIndex(period_rng, freq="D")\n other1 = period_range("1/6/2000", freq="D", periods=5)\n expected1 = rng1\n\n rng2 = PeriodIndex(period_rng, freq="D")\n other2 = period_range("1/4/2000", freq="D", periods=5)\n expected2 = PeriodIndex(["1/3/2000", "1/2/2000", "1/1/2000"], freq="D")\n\n rng3 = PeriodIndex(period_rng, freq="D")\n other3 = PeriodIndex([], freq="D")\n expected3 = rng3\n\n period_rng = [\n "2000-01-01 10:00",\n "2000-01-01 09:00",\n "2000-01-01 12:00",\n "2000-01-01 11:00",\n "2000-01-01 13:00",\n ]\n rng4 = PeriodIndex(period_rng, freq="h")\n other4 = period_range("2000-01-02 09:00", freq="h", periods=5)\n expected4 = rng4\n\n rng5 = PeriodIndex(\n ["2000-01-01 09:03", "2000-01-01 09:01", "2000-01-01 09:05"], freq="min"\n )\n other5 = PeriodIndex(["2000-01-01 09:01", "2000-01-01 09:05"], freq="min")\n expected5 = PeriodIndex(["2000-01-01 09:03"], freq="min")\n\n period_rng = [\n "2000-02-01",\n "2000-01-01",\n "2000-06-01",\n "2000-07-01",\n "2000-05-01",\n "2000-03-01",\n "2000-04-01",\n ]\n rng6 = PeriodIndex(period_rng, freq="M")\n other6 = period_range("2000-04-01", freq="M", periods=7)\n expected6 = PeriodIndex(["2000-02-01", "2000-01-01", "2000-03-01"], freq="M")\n\n period_rng = ["2003", "2007", "2006", "2005", "2004"]\n rng7 = PeriodIndex(period_rng, freq="Y")\n other7 = period_range("1998-01-01", freq="Y", periods=8)\n expected7 = PeriodIndex(["2007", "2006"], freq="Y")\n\n for rng, other, expected in [\n (rng1, other1, expected1),\n (rng2, other2, expected2),\n (rng3, other3, expected3),\n (rng4, other4, expected4),\n (rng5, other5, expected5),\n (rng6, other6, expected6),\n (rng7, other7, expected7),\n ]:\n result_difference = rng.difference(other, sort=sort)\n if sort is None and len(other):\n # We dont sort (yet?) when empty GH#24959\n expected = expected.sort_values()\n tm.assert_index_equal(result_difference, expected)\n\n def test_difference_freq(self, sort):\n # GH14323: difference of Period MUST preserve frequency\n # but the ability to union results must be preserved\n\n index = period_range("20160920", "20160925", freq="D")\n\n other = period_range("20160921", "20160924", freq="D")\n expected = PeriodIndex(["20160920", "20160925"], freq="D")\n idx_diff = index.difference(other, sort)\n tm.assert_index_equal(idx_diff, expected)\n tm.assert_attr_equal("freq", idx_diff, expected)\n\n other = period_range("20160922", "20160925", freq="D")\n idx_diff = index.difference(other, sort)\n expected = PeriodIndex(["20160920", "20160921"], freq="D")\n tm.assert_index_equal(idx_diff, expected)\n tm.assert_attr_equal("freq", idx_diff, expected)\n\n def test_intersection_equal_duplicates(self):\n # GH#38302\n idx = period_range("2011-01-01", periods=2)\n idx_dup = idx.append(idx)\n result = idx_dup.intersection(idx_dup)\n tm.assert_index_equal(result, idx)\n\n @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")\n def test_union_duplicates(self):\n # GH#36289\n idx = period_range("2011-01-01", periods=2)\n idx_dup = idx.append(idx)\n\n idx2 = period_range("2011-01-02", periods=2)\n idx2_dup = idx2.append(idx2)\n result = idx_dup.union(idx2_dup)\n\n expected = PeriodIndex(\n [\n "2011-01-01",\n "2011-01-01",\n "2011-01-02",\n "2011-01-02",\n "2011-01-03",\n "2011-01-03",\n ],\n freq="D",\n )\n tm.assert_index_equal(result, expected)\n | .venv\Lib\site-packages\pandas\tests\indexes\period\test_setops.py | test_setops.py | Python | 12,547 | 0.95 | 0.063361 | 0.048077 | python-kit | 681 | 2024-05-28T09:22:49.153610 | GPL-3.0 | true | 70355010cbae18e39a042fe922c5f5ab |
import numpy as np\nimport pytest\n\nfrom pandas import (\n Period,\n PeriodIndex,\n period_range,\n)\nimport pandas._testing as tm\n\n\nclass TestPeriodRepresentation:\n """\n Wish to match NumPy units\n """\n\n @pytest.mark.parametrize(\n "freq, base_date",\n [\n ("W-THU", "1970-01-01"),\n ("D", "1970-01-01"),\n ("B", "1970-01-01"),\n ("h", "1970-01-01"),\n ("min", "1970-01-01"),\n ("s", "1970-01-01"),\n ("ms", "1970-01-01"),\n ("us", "1970-01-01"),\n ("ns", "1970-01-01"),\n ("M", "1970-01"),\n ("Y", 1970),\n ],\n )\n @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")\n @pytest.mark.filterwarnings(\n "ignore:Period with BDay freq is deprecated:FutureWarning"\n )\n def test_freq(self, freq, base_date):\n rng = period_range(start=base_date, periods=10, freq=freq)\n exp = np.arange(10, dtype=np.int64)\n\n tm.assert_numpy_array_equal(rng.asi8, exp)\n\n\nclass TestPeriodIndexConversion:\n def test_tolist(self):\n index = period_range(freq="Y", start="1/1/2001", end="12/1/2009")\n rs = index.tolist()\n for x in rs:\n assert isinstance(x, Period)\n\n recon = PeriodIndex(rs)\n tm.assert_index_equal(index, recon)\n | .venv\Lib\site-packages\pandas\tests\indexes\period\test_tools.py | test_tools.py | Python | 1,361 | 0.85 | 0.096154 | 0 | python-kit | 532 | 2024-03-12T22:35:46.619451 | BSD-3-Clause | true | f5cf96dfc7adb0c8aee27757098d5794 |
import re\n\nimport pytest\n\nfrom pandas import (\n PeriodIndex,\n Series,\n period_range,\n)\nimport pandas._testing as tm\n\nfrom pandas.tseries import offsets\n\n\nclass TestPeriodIndex:\n def test_asfreq(self):\n pi1 = period_range(freq="Y", start="1/1/2001", end="1/1/2001")\n pi2 = period_range(freq="Q", start="1/1/2001", end="1/1/2001")\n pi3 = period_range(freq="M", start="1/1/2001", end="1/1/2001")\n pi4 = period_range(freq="D", start="1/1/2001", end="1/1/2001")\n pi5 = period_range(freq="h", start="1/1/2001", end="1/1/2001 00:00")\n pi6 = period_range(freq="Min", start="1/1/2001", end="1/1/2001 00:00")\n pi7 = period_range(freq="s", start="1/1/2001", end="1/1/2001 00:00:00")\n\n assert pi1.asfreq("Q", "s") == pi2\n assert pi1.asfreq("Q", "s") == pi2\n assert pi1.asfreq("M", "start") == pi3\n assert pi1.asfreq("D", "StarT") == pi4\n assert pi1.asfreq("h", "beGIN") == pi5\n assert pi1.asfreq("Min", "s") == pi6\n assert pi1.asfreq("s", "s") == pi7\n\n assert pi2.asfreq("Y", "s") == pi1\n assert pi2.asfreq("M", "s") == pi3\n assert pi2.asfreq("D", "s") == pi4\n assert pi2.asfreq("h", "s") == pi5\n assert pi2.asfreq("Min", "s") == pi6\n assert pi2.asfreq("s", "s") == pi7\n\n assert pi3.asfreq("Y", "s") == pi1\n assert pi3.asfreq("Q", "s") == pi2\n assert pi3.asfreq("D", "s") == pi4\n assert pi3.asfreq("h", "s") == pi5\n assert pi3.asfreq("Min", "s") == pi6\n assert pi3.asfreq("s", "s") == pi7\n\n assert pi4.asfreq("Y", "s") == pi1\n assert pi4.asfreq("Q", "s") == pi2\n assert pi4.asfreq("M", "s") == pi3\n assert pi4.asfreq("h", "s") == pi5\n assert pi4.asfreq("Min", "s") == pi6\n assert pi4.asfreq("s", "s") == pi7\n\n assert pi5.asfreq("Y", "s") == pi1\n assert pi5.asfreq("Q", "s") == pi2\n assert pi5.asfreq("M", "s") == pi3\n assert pi5.asfreq("D", "s") == pi4\n assert pi5.asfreq("Min", "s") == pi6\n assert pi5.asfreq("s", "s") == pi7\n\n assert pi6.asfreq("Y", "s") == pi1\n assert pi6.asfreq("Q", "s") == pi2\n assert pi6.asfreq("M", "s") == pi3\n assert pi6.asfreq("D", "s") == pi4\n assert pi6.asfreq("h", "s") == pi5\n assert pi6.asfreq("s", "s") == pi7\n\n assert pi7.asfreq("Y", "s") == pi1\n assert pi7.asfreq("Q", "s") == pi2\n assert pi7.asfreq("M", "s") == pi3\n assert pi7.asfreq("D", "s") == pi4\n assert pi7.asfreq("h", "s") == pi5\n assert pi7.asfreq("Min", "s") == pi6\n\n msg = "How must be one of S or E"\n with pytest.raises(ValueError, match=msg):\n pi7.asfreq("T", "foo")\n result1 = pi1.asfreq("3M")\n result2 = pi1.asfreq("M")\n expected = period_range(freq="M", start="2001-12", end="2001-12")\n tm.assert_numpy_array_equal(result1.asi8, expected.asi8)\n assert result1.freqstr == "3M"\n tm.assert_numpy_array_equal(result2.asi8, expected.asi8)\n assert result2.freqstr == "M"\n\n def test_asfreq_nat(self):\n idx = PeriodIndex(["2011-01", "2011-02", "NaT", "2011-04"], freq="M")\n result = idx.asfreq(freq="Q")\n expected = PeriodIndex(["2011Q1", "2011Q1", "NaT", "2011Q2"], freq="Q")\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize("freq", ["D", "3D"])\n def test_asfreq_mult_pi(self, freq):\n pi = PeriodIndex(["2001-01", "2001-02", "NaT", "2001-03"], freq="2M")\n\n result = pi.asfreq(freq)\n exp = PeriodIndex(["2001-02-28", "2001-03-31", "NaT", "2001-04-30"], freq=freq)\n tm.assert_index_equal(result, exp)\n assert result.freq == exp.freq\n\n result = pi.asfreq(freq, how="S")\n exp = PeriodIndex(["2001-01-01", "2001-02-01", "NaT", "2001-03-01"], freq=freq)\n tm.assert_index_equal(result, exp)\n assert result.freq == exp.freq\n\n def test_asfreq_combined_pi(self):\n pi = PeriodIndex(["2001-01-01 00:00", "2001-01-02 02:00", "NaT"], freq="h")\n exp = PeriodIndex(["2001-01-01 00:00", "2001-01-02 02:00", "NaT"], freq="25h")\n for freq, how in zip(["1D1h", "1h1D"], ["S", "E"]):\n result = pi.asfreq(freq, how=how)\n tm.assert_index_equal(result, exp)\n assert result.freq == exp.freq\n\n for freq in ["1D1h", "1h1D"]:\n pi = PeriodIndex(["2001-01-01 00:00", "2001-01-02 02:00", "NaT"], freq=freq)\n result = pi.asfreq("h")\n exp = PeriodIndex(["2001-01-02 00:00", "2001-01-03 02:00", "NaT"], freq="h")\n tm.assert_index_equal(result, exp)\n assert result.freq == exp.freq\n\n pi = PeriodIndex(["2001-01-01 00:00", "2001-01-02 02:00", "NaT"], freq=freq)\n result = pi.asfreq("h", how="S")\n exp = PeriodIndex(["2001-01-01 00:00", "2001-01-02 02:00", "NaT"], freq="h")\n tm.assert_index_equal(result, exp)\n assert result.freq == exp.freq\n\n def test_astype_asfreq(self):\n pi1 = PeriodIndex(["2011-01-01", "2011-02-01", "2011-03-01"], freq="D")\n exp = PeriodIndex(["2011-01", "2011-02", "2011-03"], freq="M")\n tm.assert_index_equal(pi1.asfreq("M"), exp)\n tm.assert_index_equal(pi1.astype("period[M]"), exp)\n\n exp = PeriodIndex(["2011-01", "2011-02", "2011-03"], freq="3M")\n tm.assert_index_equal(pi1.asfreq("3M"), exp)\n tm.assert_index_equal(pi1.astype("period[3M]"), exp)\n\n def test_asfreq_with_different_n(self):\n ser = Series([1, 2], index=PeriodIndex(["2020-01", "2020-03"], freq="2M"))\n result = ser.asfreq("M")\n\n excepted = Series([1, 2], index=PeriodIndex(["2020-02", "2020-04"], freq="M"))\n tm.assert_series_equal(result, excepted)\n\n @pytest.mark.parametrize(\n "freq",\n [\n "2BMS",\n "2YS-MAR",\n "2bh",\n ],\n )\n def test_pi_asfreq_not_supported_frequency(self, freq):\n # GH#55785\n msg = f"{freq[1:]} is not supported as period frequency"\n\n pi = PeriodIndex(["2020-01-01", "2021-01-01"], freq="M")\n with pytest.raises(ValueError, match=msg):\n pi.asfreq(freq=freq)\n\n @pytest.mark.parametrize(\n "freq",\n [\n "2BME",\n "2YE-MAR",\n "2QE",\n ],\n )\n def test_pi_asfreq_invalid_frequency(self, freq):\n # GH#55785\n msg = f"Invalid frequency: {freq}"\n\n pi = PeriodIndex(["2020-01-01", "2021-01-01"], freq="M")\n with pytest.raises(ValueError, match=msg):\n pi.asfreq(freq=freq)\n\n @pytest.mark.parametrize(\n "freq",\n [\n offsets.MonthBegin(2),\n offsets.BusinessMonthEnd(2),\n ],\n )\n def test_pi_asfreq_invalid_baseoffset(self, freq):\n # GH#56945\n msg = re.escape(f"{freq} is not supported as period frequency")\n\n pi = PeriodIndex(["2020-01-01", "2021-01-01"], freq="M")\n with pytest.raises(ValueError, match=msg):\n pi.asfreq(freq=freq)\n | .venv\Lib\site-packages\pandas\tests\indexes\period\methods\test_asfreq.py | test_asfreq.py | Python | 7,080 | 0.95 | 0.063492 | 0.018868 | python-kit | 999 | 2023-10-31T18:09:11.084026 | Apache-2.0 | true | 97071265c98a577ecc9ecabc0cb52bd6 |
import numpy as np\nimport pytest\n\nfrom pandas import (\n CategoricalIndex,\n DatetimeIndex,\n Index,\n NaT,\n Period,\n PeriodIndex,\n period_range,\n)\nimport pandas._testing as tm\n\n\nclass TestPeriodIndexAsType:\n @pytest.mark.parametrize("dtype", [float, "timedelta64", "timedelta64[ns]"])\n def test_astype_raises(self, dtype):\n # GH#13149, GH#13209\n idx = PeriodIndex(["2016-05-16", "NaT", NaT, np.nan], freq="D")\n msg = "Cannot cast PeriodIndex to dtype"\n with pytest.raises(TypeError, match=msg):\n idx.astype(dtype)\n\n def test_astype_conversion(self, using_infer_string):\n # GH#13149, GH#13209\n idx = PeriodIndex(["2016-05-16", "NaT", NaT, np.nan], freq="D", name="idx")\n\n result = idx.astype(object)\n expected = Index(\n [Period("2016-05-16", freq="D")] + [Period(NaT, freq="D")] * 3,\n dtype="object",\n name="idx",\n )\n tm.assert_index_equal(result, expected)\n\n result = idx.astype(np.int64)\n expected = Index(\n [16937] + [-9223372036854775808] * 3, dtype=np.int64, name="idx"\n )\n tm.assert_index_equal(result, expected)\n\n result = idx.astype(str)\n if using_infer_string:\n expected = Index(\n [str(x) if x is not NaT else None for x in idx], name="idx", dtype="str"\n )\n else:\n expected = Index([str(x) for x in idx], name="idx", dtype=object)\n tm.assert_index_equal(result, expected)\n\n idx = period_range("1990", "2009", freq="Y", name="idx")\n result = idx.astype("i8")\n tm.assert_index_equal(result, Index(idx.asi8, name="idx"))\n tm.assert_numpy_array_equal(result.values, idx.asi8)\n\n def test_astype_uint(self):\n arr = period_range("2000", periods=2, name="idx")\n\n with pytest.raises(TypeError, match=r"Do obj.astype\('int64'\)"):\n arr.astype("uint64")\n with pytest.raises(TypeError, match=r"Do obj.astype\('int64'\)"):\n arr.astype("uint32")\n\n def test_astype_object(self):\n idx = PeriodIndex([], freq="M")\n\n exp = np.array([], dtype=object)\n tm.assert_numpy_array_equal(idx.astype(object).values, exp)\n tm.assert_numpy_array_equal(idx._mpl_repr(), exp)\n\n idx = PeriodIndex(["2011-01", NaT], freq="M")\n\n exp = np.array([Period("2011-01", freq="M"), NaT], dtype=object)\n tm.assert_numpy_array_equal(idx.astype(object).values, exp)\n tm.assert_numpy_array_equal(idx._mpl_repr(), exp)\n\n exp = np.array([Period("2011-01-01", freq="D"), NaT], dtype=object)\n idx = PeriodIndex(["2011-01-01", NaT], freq="D")\n tm.assert_numpy_array_equal(idx.astype(object).values, exp)\n tm.assert_numpy_array_equal(idx._mpl_repr(), exp)\n\n # TODO: de-duplicate this version (from test_ops) with the one above\n # (from test_period)\n def test_astype_object2(self):\n idx = period_range(start="2013-01-01", periods=4, freq="M", name="idx")\n expected_list = [\n Period("2013-01-31", freq="M"),\n Period("2013-02-28", freq="M"),\n Period("2013-03-31", freq="M"),\n Period("2013-04-30", freq="M"),\n ]\n expected = Index(expected_list, dtype=object, name="idx")\n result = idx.astype(object)\n assert isinstance(result, Index)\n assert result.dtype == object\n tm.assert_index_equal(result, expected)\n assert result.name == expected.name\n assert idx.tolist() == expected_list\n\n idx = PeriodIndex(\n ["2013-01-01", "2013-01-02", "NaT", "2013-01-04"], freq="D", name="idx"\n )\n expected_list = [\n Period("2013-01-01", freq="D"),\n Period("2013-01-02", freq="D"),\n Period("NaT", freq="D"),\n Period("2013-01-04", freq="D"),\n ]\n expected = Index(expected_list, dtype=object, name="idx")\n result = idx.astype(object)\n assert isinstance(result, Index)\n assert result.dtype == object\n tm.assert_index_equal(result, expected)\n for i in [0, 1, 3]:\n assert result[i] == expected[i]\n assert result[2] is NaT\n assert result.name == expected.name\n\n result_list = idx.tolist()\n for i in [0, 1, 3]:\n assert result_list[i] == expected_list[i]\n assert result_list[2] is NaT\n\n def test_astype_category(self):\n obj = period_range("2000", periods=2, name="idx")\n result = obj.astype("category")\n expected = CategoricalIndex(\n [Period("2000-01-01", freq="D"), Period("2000-01-02", freq="D")], name="idx"\n )\n tm.assert_index_equal(result, expected)\n\n result = obj._data.astype("category")\n expected = expected.values\n tm.assert_categorical_equal(result, expected)\n\n def test_astype_array_fallback(self):\n obj = period_range("2000", periods=2, name="idx")\n result = obj.astype(bool)\n expected = Index(np.array([True, True]), name="idx")\n tm.assert_index_equal(result, expected)\n\n result = obj._data.astype(bool)\n expected = np.array([True, True])\n tm.assert_numpy_array_equal(result, expected)\n\n def test_period_astype_to_timestamp(self, unit):\n # GH#55958\n pi = PeriodIndex(["2011-01", "2011-02", "2011-03"], freq="M")\n\n exp = DatetimeIndex(\n ["2011-01-01", "2011-02-01", "2011-03-01"], tz="US/Eastern"\n ).as_unit(unit)\n res = pi.astype(f"datetime64[{unit}, US/Eastern]")\n tm.assert_index_equal(res, exp)\n assert res.freq == exp.freq\n | .venv\Lib\site-packages\pandas\tests\indexes\period\methods\test_astype.py | test_astype.py | Python | 5,671 | 0.95 | 0.096154 | 0.037879 | vue-tools | 58 | 2025-04-20T17:31:59.029388 | GPL-3.0 | true | 5cf23a5870b60b5c9a8d0bc252d90467 |
import numpy as np\n\nfrom pandas import PeriodIndex\nimport pandas._testing as tm\n\n\nclass TestFactorize:\n def test_factorize_period(self):\n idx1 = PeriodIndex(\n ["2014-01", "2014-01", "2014-02", "2014-02", "2014-03", "2014-03"],\n freq="M",\n )\n\n exp_arr = np.array([0, 0, 1, 1, 2, 2], dtype=np.intp)\n exp_idx = PeriodIndex(["2014-01", "2014-02", "2014-03"], freq="M")\n\n arr, idx = idx1.factorize()\n tm.assert_numpy_array_equal(arr, exp_arr)\n tm.assert_index_equal(idx, exp_idx)\n\n arr, idx = idx1.factorize(sort=True)\n tm.assert_numpy_array_equal(arr, exp_arr)\n tm.assert_index_equal(idx, exp_idx)\n\n def test_factorize_period_nonmonotonic(self):\n idx2 = PeriodIndex(\n ["2014-03", "2014-03", "2014-02", "2014-01", "2014-03", "2014-01"],\n freq="M",\n )\n exp_idx = PeriodIndex(["2014-01", "2014-02", "2014-03"], freq="M")\n\n exp_arr = np.array([2, 2, 1, 0, 2, 0], dtype=np.intp)\n arr, idx = idx2.factorize(sort=True)\n tm.assert_numpy_array_equal(arr, exp_arr)\n tm.assert_index_equal(idx, exp_idx)\n\n exp_arr = np.array([0, 0, 1, 2, 0, 2], dtype=np.intp)\n exp_idx = PeriodIndex(["2014-03", "2014-02", "2014-01"], freq="M")\n arr, idx = idx2.factorize()\n tm.assert_numpy_array_equal(arr, exp_arr)\n tm.assert_index_equal(idx, exp_idx)\n | .venv\Lib\site-packages\pandas\tests\indexes\period\methods\test_factorize.py | test_factorize.py | Python | 1,425 | 0.85 | 0.073171 | 0 | react-lib | 327 | 2023-07-25T17:14:24.373337 | BSD-3-Clause | true | 707810f00e5c2c038e215b9539bd2e56 |
from pandas import (\n Index,\n NaT,\n Period,\n PeriodIndex,\n)\nimport pandas._testing as tm\n\n\nclass TestFillNA:\n def test_fillna_period(self):\n # GH#11343\n idx = PeriodIndex(["2011-01-01 09:00", NaT, "2011-01-01 11:00"], freq="h")\n\n exp = PeriodIndex(\n ["2011-01-01 09:00", "2011-01-01 10:00", "2011-01-01 11:00"], freq="h"\n )\n result = idx.fillna(Period("2011-01-01 10:00", freq="h"))\n tm.assert_index_equal(result, exp)\n\n exp = Index(\n [\n Period("2011-01-01 09:00", freq="h"),\n "x",\n Period("2011-01-01 11:00", freq="h"),\n ],\n dtype=object,\n )\n result = idx.fillna("x")\n tm.assert_index_equal(result, exp)\n\n exp = Index(\n [\n Period("2011-01-01 09:00", freq="h"),\n Period("2011-01-01", freq="D"),\n Period("2011-01-01 11:00", freq="h"),\n ],\n dtype=object,\n )\n result = idx.fillna(Period("2011-01-01", freq="D"))\n tm.assert_index_equal(result, exp)\n | .venv\Lib\site-packages\pandas\tests\indexes\period\methods\test_fillna.py | test_fillna.py | Python | 1,125 | 0.95 | 0.04878 | 0.027778 | python-kit | 850 | 2024-07-13T12:07:46.948919 | BSD-3-Clause | true | ec6099dee3130d2256bd2ddbe0d6a52d |
import numpy as np\nimport pytest\n\nfrom pandas import (\n NaT,\n PeriodIndex,\n period_range,\n)\nimport pandas._testing as tm\n\n\nclass TestInsert:\n @pytest.mark.parametrize("na", [np.nan, NaT, None])\n def test_insert(self, na):\n # GH#18295 (test missing)\n expected = PeriodIndex(["2017Q1", NaT, "2017Q2", "2017Q3", "2017Q4"], freq="Q")\n result = period_range("2017Q1", periods=4, freq="Q").insert(1, na)\n tm.assert_index_equal(result, expected)\n | .venv\Lib\site-packages\pandas\tests\indexes\period\methods\test_insert.py | test_insert.py | Python | 482 | 0.95 | 0.111111 | 0.066667 | vue-tools | 215 | 2024-04-06T13:04:54.229302 | Apache-2.0 | true | 88267d9d5f619c78f066165e9489d37e |
import pytest\n\nfrom pandas import PeriodIndex\n\n\ndef test_is_full():\n index = PeriodIndex([2005, 2007, 2009], freq="Y")\n assert not index.is_full\n\n index = PeriodIndex([2005, 2006, 2007], freq="Y")\n assert index.is_full\n\n index = PeriodIndex([2005, 2005, 2007], freq="Y")\n assert not index.is_full\n\n index = PeriodIndex([2005, 2005, 2006], freq="Y")\n assert index.is_full\n\n index = PeriodIndex([2006, 2005, 2005], freq="Y")\n with pytest.raises(ValueError, match="Index is not monotonic"):\n index.is_full\n\n assert index[:0].is_full\n | .venv\Lib\site-packages\pandas\tests\indexes\period\methods\test_is_full.py | test_is_full.py | Python | 570 | 0.85 | 0.043478 | 0 | awesome-app | 545 | 2024-07-18T06:24:54.369982 | GPL-3.0 | true | 9da1df4e18377f9c6fbf8bd66738b265 |
import numpy as np\nimport pytest\n\nfrom pandas import (\n PeriodIndex,\n period_range,\n)\nimport pandas._testing as tm\n\n\nclass TestRepeat:\n @pytest.mark.parametrize("use_numpy", [True, False])\n @pytest.mark.parametrize(\n "index",\n [\n period_range("2000-01-01", periods=3, freq="D"),\n period_range("2001-01-01", periods=3, freq="2D"),\n PeriodIndex(["2001-01", "NaT", "2003-01"], freq="M"),\n ],\n )\n def test_repeat_freqstr(self, index, use_numpy):\n # GH#10183\n expected = PeriodIndex([per for per in index for _ in range(3)])\n result = np.repeat(index, 3) if use_numpy else index.repeat(3)\n tm.assert_index_equal(result, expected)\n assert result.freqstr == index.freqstr\n | .venv\Lib\site-packages\pandas\tests\indexes\period\methods\test_repeat.py | test_repeat.py | Python | 772 | 0.95 | 0.192308 | 0.043478 | node-utils | 29 | 2024-03-13T04:29:32.338256 | BSD-3-Clause | true | 0b845915b7e0ff76d50ac2a47e81bff4 |
import numpy as np\nimport pytest\n\nfrom pandas import (\n PeriodIndex,\n period_range,\n)\nimport pandas._testing as tm\n\n\nclass TestPeriodIndexShift:\n # ---------------------------------------------------------------\n # PeriodIndex.shift is used by __add__ and __sub__\n\n def test_pi_shift_ndarray(self):\n idx = PeriodIndex(\n ["2011-01", "2011-02", "NaT", "2011-04"], freq="M", name="idx"\n )\n result = idx.shift(np.array([1, 2, 3, 4]))\n expected = PeriodIndex(\n ["2011-02", "2011-04", "NaT", "2011-08"], freq="M", name="idx"\n )\n tm.assert_index_equal(result, expected)\n\n result = idx.shift(np.array([1, -2, 3, -4]))\n expected = PeriodIndex(\n ["2011-02", "2010-12", "NaT", "2010-12"], freq="M", name="idx"\n )\n tm.assert_index_equal(result, expected)\n\n def test_shift(self):\n pi1 = period_range(freq="Y", start="1/1/2001", end="12/1/2009")\n pi2 = period_range(freq="Y", start="1/1/2002", end="12/1/2010")\n\n tm.assert_index_equal(pi1.shift(0), pi1)\n\n assert len(pi1) == len(pi2)\n tm.assert_index_equal(pi1.shift(1), pi2)\n\n pi1 = period_range(freq="Y", start="1/1/2001", end="12/1/2009")\n pi2 = period_range(freq="Y", start="1/1/2000", end="12/1/2008")\n assert len(pi1) == len(pi2)\n tm.assert_index_equal(pi1.shift(-1), pi2)\n\n pi1 = period_range(freq="M", start="1/1/2001", end="12/1/2009")\n pi2 = period_range(freq="M", start="2/1/2001", end="1/1/2010")\n assert len(pi1) == len(pi2)\n tm.assert_index_equal(pi1.shift(1), pi2)\n\n pi1 = period_range(freq="M", start="1/1/2001", end="12/1/2009")\n pi2 = period_range(freq="M", start="12/1/2000", end="11/1/2009")\n assert len(pi1) == len(pi2)\n tm.assert_index_equal(pi1.shift(-1), pi2)\n\n pi1 = period_range(freq="D", start="1/1/2001", end="12/1/2009")\n pi2 = period_range(freq="D", start="1/2/2001", end="12/2/2009")\n assert len(pi1) == len(pi2)\n tm.assert_index_equal(pi1.shift(1), pi2)\n\n pi1 = period_range(freq="D", start="1/1/2001", end="12/1/2009")\n pi2 = period_range(freq="D", start="12/31/2000", end="11/30/2009")\n assert len(pi1) == len(pi2)\n tm.assert_index_equal(pi1.shift(-1), pi2)\n\n def test_shift_corner_cases(self):\n # GH#9903\n idx = PeriodIndex([], name="xxx", freq="h")\n\n msg = "`freq` argument is not supported for PeriodIndex.shift"\n with pytest.raises(TypeError, match=msg):\n # period shift doesn't accept freq\n idx.shift(1, freq="h")\n\n tm.assert_index_equal(idx.shift(0), idx)\n tm.assert_index_equal(idx.shift(3), idx)\n\n idx = PeriodIndex(\n ["2011-01-01 10:00", "2011-01-01 11:00", "2011-01-01 12:00"],\n name="xxx",\n freq="h",\n )\n tm.assert_index_equal(idx.shift(0), idx)\n exp = PeriodIndex(\n ["2011-01-01 13:00", "2011-01-01 14:00", "2011-01-01 15:00"],\n name="xxx",\n freq="h",\n )\n tm.assert_index_equal(idx.shift(3), exp)\n exp = PeriodIndex(\n ["2011-01-01 07:00", "2011-01-01 08:00", "2011-01-01 09:00"],\n name="xxx",\n freq="h",\n )\n tm.assert_index_equal(idx.shift(-3), exp)\n\n def test_shift_nat(self):\n idx = PeriodIndex(\n ["2011-01", "2011-02", "NaT", "2011-04"], freq="M", name="idx"\n )\n result = idx.shift(1)\n expected = PeriodIndex(\n ["2011-02", "2011-03", "NaT", "2011-05"], freq="M", name="idx"\n )\n tm.assert_index_equal(result, expected)\n assert result.name == expected.name\n\n def test_shift_gh8083(self):\n # test shift for PeriodIndex\n # GH#8083\n drange = period_range("20130101", periods=5, freq="D")\n result = drange.shift(1)\n expected = PeriodIndex(\n ["2013-01-02", "2013-01-03", "2013-01-04", "2013-01-05", "2013-01-06"],\n freq="D",\n )\n tm.assert_index_equal(result, expected)\n\n def test_shift_periods(self):\n # GH #22458 : argument 'n' was deprecated in favor of 'periods'\n idx = period_range(freq="Y", start="1/1/2001", end="12/1/2009")\n tm.assert_index_equal(idx.shift(periods=0), idx)\n tm.assert_index_equal(idx.shift(0), idx)\n | .venv\Lib\site-packages\pandas\tests\indexes\period\methods\test_shift.py | test_shift.py | Python | 4,405 | 0.95 | 0.07377 | 0.068627 | awesome-app | 859 | 2025-02-24T07:31:14.880220 | Apache-2.0 | true | fa48d0b29999070897b9d248c7c4ec88 |
from datetime import datetime\n\nimport numpy as np\nimport pytest\n\nfrom pandas import (\n DatetimeIndex,\n NaT,\n PeriodIndex,\n Timedelta,\n Timestamp,\n date_range,\n period_range,\n)\nimport pandas._testing as tm\n\n\nclass TestToTimestamp:\n def test_to_timestamp_non_contiguous(self):\n # GH#44100\n dti = date_range("2021-10-18", periods=9, freq="D")\n pi = dti.to_period()\n\n result = pi[::2].to_timestamp()\n expected = dti[::2]\n tm.assert_index_equal(result, expected)\n\n result = pi._data[::2].to_timestamp()\n expected = dti._data[::2]\n # TODO: can we get the freq to round-trip?\n tm.assert_datetime_array_equal(result, expected, check_freq=False)\n\n result = pi[::-1].to_timestamp()\n expected = dti[::-1]\n tm.assert_index_equal(result, expected)\n\n result = pi._data[::-1].to_timestamp()\n expected = dti._data[::-1]\n tm.assert_datetime_array_equal(result, expected, check_freq=False)\n\n result = pi[::2][::-1].to_timestamp()\n expected = dti[::2][::-1]\n tm.assert_index_equal(result, expected)\n\n result = pi._data[::2][::-1].to_timestamp()\n expected = dti._data[::2][::-1]\n tm.assert_datetime_array_equal(result, expected, check_freq=False)\n\n def test_to_timestamp_freq(self):\n idx = period_range("2017", periods=12, freq="Y-DEC")\n result = idx.to_timestamp()\n expected = date_range("2017", periods=12, freq="YS-JAN")\n tm.assert_index_equal(result, expected)\n\n def test_to_timestamp_pi_nat(self):\n # GH#7228\n index = PeriodIndex(["NaT", "2011-01", "2011-02"], freq="M", name="idx")\n\n result = index.to_timestamp("D")\n expected = DatetimeIndex(\n [NaT, datetime(2011, 1, 1), datetime(2011, 2, 1)],\n dtype="M8[ns]",\n name="idx",\n )\n tm.assert_index_equal(result, expected)\n assert result.name == "idx"\n\n result2 = result.to_period(freq="M")\n tm.assert_index_equal(result2, index)\n assert result2.name == "idx"\n\n result3 = result.to_period(freq="3M")\n exp = PeriodIndex(["NaT", "2011-01", "2011-02"], freq="3M", name="idx")\n tm.assert_index_equal(result3, exp)\n assert result3.freqstr == "3M"\n\n msg = "Frequency must be positive, because it represents span: -2Y"\n with pytest.raises(ValueError, match=msg):\n result.to_period(freq="-2Y")\n\n def test_to_timestamp_preserve_name(self):\n index = period_range(freq="Y", start="1/1/2001", end="12/1/2009", name="foo")\n assert index.name == "foo"\n\n conv = index.to_timestamp("D")\n assert conv.name == "foo"\n\n def test_to_timestamp_quarterly_bug(self):\n years = np.arange(1960, 2000).repeat(4)\n quarters = np.tile(list(range(1, 5)), 40)\n\n pindex = PeriodIndex.from_fields(year=years, quarter=quarters)\n\n stamps = pindex.to_timestamp("D", "end")\n expected = DatetimeIndex([x.to_timestamp("D", "end") for x in pindex])\n tm.assert_index_equal(stamps, expected)\n assert stamps.freq == expected.freq\n\n def test_to_timestamp_pi_mult(self):\n idx = PeriodIndex(["2011-01", "NaT", "2011-02"], freq="2M", name="idx")\n\n result = idx.to_timestamp()\n expected = DatetimeIndex(\n ["2011-01-01", "NaT", "2011-02-01"], dtype="M8[ns]", name="idx"\n )\n tm.assert_index_equal(result, expected)\n\n result = idx.to_timestamp(how="E")\n expected = DatetimeIndex(\n ["2011-02-28", "NaT", "2011-03-31"], dtype="M8[ns]", name="idx"\n )\n expected = expected + Timedelta(1, "D") - Timedelta(1, "ns")\n tm.assert_index_equal(result, expected)\n\n def test_to_timestamp_pi_combined(self):\n idx = period_range(start="2011", periods=2, freq="1D1h", name="idx")\n\n result = idx.to_timestamp()\n expected = DatetimeIndex(\n ["2011-01-01 00:00", "2011-01-02 01:00"], dtype="M8[ns]", name="idx"\n )\n tm.assert_index_equal(result, expected)\n\n result = idx.to_timestamp(how="E")\n expected = DatetimeIndex(\n ["2011-01-02 00:59:59", "2011-01-03 01:59:59"], name="idx", dtype="M8[ns]"\n )\n expected = expected + Timedelta(1, "s") - Timedelta(1, "ns")\n tm.assert_index_equal(result, expected)\n\n result = idx.to_timestamp(how="E", freq="h")\n expected = DatetimeIndex(\n ["2011-01-02 00:00", "2011-01-03 01:00"], dtype="M8[ns]", name="idx"\n )\n expected = expected + Timedelta(1, "h") - Timedelta(1, "ns")\n tm.assert_index_equal(result, expected)\n\n def test_to_timestamp_1703(self):\n index = period_range("1/1/2012", periods=4, freq="D")\n\n result = index.to_timestamp()\n assert result[0] == Timestamp("1/1/2012")\n | .venv\Lib\site-packages\pandas\tests\indexes\period\methods\test_to_timestamp.py | test_to_timestamp.py | Python | 4,888 | 0.95 | 0.070423 | 0.026786 | node-utils | 880 | 2023-09-05T20:34:54.906647 | GPL-3.0 | true | a26bc66de1f71e265eb9f7cce7a08524 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\period\methods\__pycache__\test_asfreq.cpython-313.pyc | test_asfreq.cpython-313.pyc | Other | 11,220 | 0.8 | 0 | 0 | react-lib | 23 | 2023-12-19T00:12:59.262785 | MIT | true | 8fb3a8edc050c0791d1d60f95fa85107 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\period\methods\__pycache__\test_astype.cpython-313.pyc | test_astype.cpython-313.pyc | Other | 9,210 | 0.8 | 0 | 0 | vue-tools | 727 | 2025-07-09T04:47:52.193794 | GPL-3.0 | true | 8cce93f1f6cecb6ce396105fabdb134e |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\period\methods\__pycache__\test_factorize.cpython-313.pyc | test_factorize.cpython-313.pyc | Other | 2,446 | 0.8 | 0 | 0 | node-utils | 58 | 2025-01-03T05:52:13.874434 | BSD-3-Clause | true | aa3a74dc2fa213af03a7dd4d419ed228 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\period\methods\__pycache__\test_fillna.cpython-313.pyc | test_fillna.cpython-313.pyc | Other | 1,627 | 0.8 | 0 | 0 | vue-tools | 974 | 2024-09-05T00:13:57.825363 | GPL-3.0 | true | 6b017950be5a7e55b3183a31c5ef0966 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\period\methods\__pycache__\test_insert.cpython-313.pyc | test_insert.cpython-313.pyc | Other | 1,262 | 0.8 | 0 | 0 | react-lib | 411 | 2023-12-10T14:30:03.920343 | GPL-3.0 | true | 3ba038696df6158e5b0845a6e48507a1 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\period\methods\__pycache__\test_is_full.cpython-313.pyc | test_is_full.cpython-313.pyc | Other | 1,187 | 0.7 | 0 | 0 | python-kit | 698 | 2024-01-08T03:16:35.049955 | GPL-3.0 | true | 7f09c885e22bccab0043e7c144bccf4c |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\period\methods\__pycache__\test_repeat.cpython-313.pyc | test_repeat.cpython-313.pyc | Other | 1,677 | 0.7 | 0 | 0 | node-utils | 544 | 2025-03-02T20:10:02.000651 | GPL-3.0 | true | 5c10598649fc87c76ebb7a03efac9aa9 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\period\methods\__pycache__\test_shift.cpython-313.pyc | test_shift.cpython-313.pyc | Other | 6,174 | 0.8 | 0.017544 | 0 | node-utils | 874 | 2023-12-31T04:34:41.541213 | Apache-2.0 | true | cb4cc0f864ddbb1c716e0ba7905f2c39 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\period\methods\__pycache__\test_to_timestamp.cpython-313.pyc | test_to_timestamp.cpython-313.pyc | Other | 7,674 | 0.8 | 0 | 0 | node-utils | 331 | 2023-11-17T21:18:14.629107 | GPL-3.0 | true | 9dbff71823737cbfbe8904644dc82d9d |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\period\methods\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 210 | 0.7 | 0 | 0 | node-utils | 896 | 2024-02-03T22:00:25.865659 | BSD-3-Clause | true | 11de00e461bea9a562ad35740db75170 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\period\__pycache__\test_constructors.cpython-313.pyc | test_constructors.cpython-313.pyc | Other | 43,701 | 0.95 | 0.00495 | 0.003333 | node-utils | 485 | 2023-08-23T07:20:52.456372 | MIT | true | 425adfcce2a8eba6b3201c843b441ca6 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\period\__pycache__\test_formats.cpython-313.pyc | test_formats.cpython-313.pyc | Other | 16,143 | 0.8 | 0 | 0.018868 | vue-tools | 511 | 2025-05-04T19:02:16.370728 | GPL-3.0 | true | 3dea3401e733eb8ca964778bc06b8640 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\period\__pycache__\test_freq_attr.cpython-313.pyc | test_freq_attr.cpython-313.pyc | Other | 1,447 | 0.7 | 0 | 0 | node-utils | 651 | 2025-03-24T23:06:02.676763 | MIT | true | 9aac0c995a98eb77d16a7b340dcadfe1 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\period\__pycache__\test_indexing.cpython-313.pyc | test_indexing.cpython-313.pyc | Other | 42,683 | 0.8 | 0.003854 | 0.005871 | python-kit | 605 | 2024-12-22T23:22:35.589496 | MIT | true | c35750738b2e09be25f7d91bc097ec87 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\period\__pycache__\test_join.cpython-313.pyc | test_join.cpython-313.pyc | Other | 3,777 | 0.8 | 0 | 0 | python-kit | 683 | 2024-09-10T12:58:36.751192 | Apache-2.0 | true | 602be76a1ab44619fc5d804aa35bf69a |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\period\__pycache__\test_monotonic.cpython-313.pyc | test_monotonic.cpython-313.pyc | Other | 1,833 | 0.8 | 0 | 0.222222 | awesome-app | 903 | 2024-05-08T12:37:50.047611 | GPL-3.0 | true | 8f1af2b77022a8c5bed38f07980869c0 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\period\__pycache__\test_partial_slicing.cpython-313.pyc | test_partial_slicing.cpython-313.pyc | Other | 11,980 | 0.95 | 0 | 0 | vue-tools | 470 | 2025-06-05T00:49:15.961374 | Apache-2.0 | true | d23ccd56a93d9f961d136bd2bc751815 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\period\__pycache__\test_period.cpython-313.pyc | test_period.cpython-313.pyc | Other | 13,599 | 0.8 | 0 | 0 | vue-tools | 336 | 2024-07-31T20:27:17.733438 | MIT | true | 82de385f084056a5929dd31a92596363 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\period\__pycache__\test_period_range.cpython-313.pyc | test_period_range.cpython-313.pyc | Other | 12,667 | 0.95 | 0 | 0 | awesome-app | 154 | 2023-11-30T22:32:40.897894 | BSD-3-Clause | true | 49be4f45aa8862eec8e436585f2eb70e |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\period\__pycache__\test_pickle.cpython-313.pyc | test_pickle.cpython-313.pyc | Other | 1,735 | 0.8 | 0 | 0 | python-kit | 428 | 2024-04-02T17:53:53.963719 | BSD-3-Clause | true | f2053d2ea8e7bb07c30e349cacee7f0e |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\period\__pycache__\test_resolution.cpython-313.pyc | test_resolution.cpython-313.pyc | Other | 1,102 | 0.8 | 0 | 0 | vue-tools | 27 | 2024-07-28T04:19:56.025457 | BSD-3-Clause | true | 2c12c0cad846c464d717c497244c9c4c |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\period\__pycache__\test_scalar_compat.cpython-313.pyc | test_scalar_compat.cpython-313.pyc | Other | 2,450 | 0.8 | 0.037037 | 0 | awesome-app | 421 | 2023-12-04T22:44:14.943740 | GPL-3.0 | true | 049bf13c814189832cc3bfbc555cfd6e |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\period\__pycache__\test_searchsorted.cpython-313.pyc | test_searchsorted.cpython-313.pyc | Other | 4,829 | 0.95 | 0 | 0 | vue-tools | 88 | 2023-09-15T14:53:41.528718 | GPL-3.0 | true | e195d8ad69b4b4b4a8a96ee9def3848e |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\period\__pycache__\test_setops.cpython-313.pyc | test_setops.cpython-313.pyc | Other | 11,544 | 0.8 | 0 | 0 | react-lib | 341 | 2025-06-03T15:01:07.687567 | MIT | true | 782686691b17bf5f3397a5fbf19a11b6 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\period\__pycache__\test_tools.cpython-313.pyc | test_tools.cpython-313.pyc | Other | 2,453 | 0.8 | 0 | 0 | vue-tools | 865 | 2024-05-13T14:22:20.213074 | Apache-2.0 | true | ce6ecc5572b26dd360127f69a77ba365 |
\n\n | .venv\Lib\site-packages\pandas\tests\indexes\period\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 202 | 0.7 | 0 | 0 | python-kit | 120 | 2024-03-18T04:11:31.547661 | Apache-2.0 | true | 7115769e770dd5dd55205f3dee7cceea |
from datetime import datetime\n\nimport numpy as np\nimport pytest\n\nfrom pandas import (\n Index,\n RangeIndex,\n Series,\n)\nimport pandas._testing as tm\n\n\nclass TestRangeIndexConstructors:\n @pytest.mark.parametrize("name", [None, "foo"])\n @pytest.mark.parametrize(\n "args, kwargs, start, stop, step",\n [\n ((5,), {}, 0, 5, 1),\n ((1, 5), {}, 1, 5, 1),\n ((1, 5, 2), {}, 1, 5, 2),\n ((0,), {}, 0, 0, 1),\n ((0, 0), {}, 0, 0, 1),\n ((), {"start": 0}, 0, 0, 1),\n ((), {"stop": 0}, 0, 0, 1),\n ],\n )\n def test_constructor(self, args, kwargs, start, stop, step, name):\n result = RangeIndex(*args, name=name, **kwargs)\n expected = Index(np.arange(start, stop, step, dtype=np.int64), name=name)\n assert isinstance(result, RangeIndex)\n assert result.name is name\n assert result._range == range(start, stop, step)\n tm.assert_index_equal(result, expected, exact="equiv")\n\n def test_constructor_invalid_args(self):\n msg = "RangeIndex\\(\\.\\.\\.\\) must be called with integers"\n with pytest.raises(TypeError, match=msg):\n RangeIndex()\n\n with pytest.raises(TypeError, match=msg):\n RangeIndex(name="Foo")\n\n # we don't allow on a bare Index\n msg = (\n r"Index\(\.\.\.\) must be called with a collection of some "\n r"kind, 0 was passed"\n )\n with pytest.raises(TypeError, match=msg):\n Index(0)\n\n @pytest.mark.parametrize(\n "args",\n [\n Index(["a", "b"]),\n Series(["a", "b"]),\n np.array(["a", "b"]),\n [],\n np.arange(0, 10),\n np.array([1]),\n [1],\n ],\n )\n def test_constructor_additional_invalid_args(self, args):\n msg = f"Value needs to be a scalar value, was type {type(args).__name__}"\n with pytest.raises(TypeError, match=msg):\n RangeIndex(args)\n\n @pytest.mark.parametrize("args", ["foo", datetime(2000, 1, 1, 0, 0)])\n def test_constructor_invalid_args_wrong_type(self, args):\n msg = f"Wrong type {type(args)} for value {args}"\n with pytest.raises(TypeError, match=msg):\n RangeIndex(args)\n\n def test_constructor_same(self):\n # pass thru w and w/o copy\n index = RangeIndex(1, 5, 2)\n result = RangeIndex(index, copy=False)\n assert result.identical(index)\n\n result = RangeIndex(index, copy=True)\n tm.assert_index_equal(result, index, exact=True)\n\n result = RangeIndex(index)\n tm.assert_index_equal(result, index, exact=True)\n\n with pytest.raises(\n ValueError,\n match="Incorrect `dtype` passed: expected signed integer, received float64",\n ):\n RangeIndex(index, dtype="float64")\n\n def test_constructor_range_object(self):\n result = RangeIndex(range(1, 5, 2))\n expected = RangeIndex(1, 5, 2)\n tm.assert_index_equal(result, expected, exact=True)\n\n def test_constructor_range(self):\n result = RangeIndex.from_range(range(1, 5, 2))\n expected = RangeIndex(1, 5, 2)\n tm.assert_index_equal(result, expected, exact=True)\n\n result = RangeIndex.from_range(range(5, 6))\n expected = RangeIndex(5, 6, 1)\n tm.assert_index_equal(result, expected, exact=True)\n\n # an invalid range\n result = RangeIndex.from_range(range(5, 1))\n expected = RangeIndex(0, 0, 1)\n tm.assert_index_equal(result, expected, exact=True)\n\n result = RangeIndex.from_range(range(5))\n expected = RangeIndex(0, 5, 1)\n tm.assert_index_equal(result, expected, exact=True)\n\n result = Index(range(1, 5, 2))\n expected = RangeIndex(1, 5, 2)\n tm.assert_index_equal(result, expected, exact=True)\n\n msg = (\n r"(RangeIndex.)?from_range\(\) got an unexpected keyword argument( 'copy')?"\n )\n with pytest.raises(TypeError, match=msg):\n RangeIndex.from_range(range(10), copy=True)\n\n def test_constructor_name(self):\n # GH#12288\n orig = RangeIndex(10)\n orig.name = "original"\n\n copy = RangeIndex(orig)\n copy.name = "copy"\n\n assert orig.name == "original"\n assert copy.name == "copy"\n\n new = Index(copy)\n assert new.name == "copy"\n\n new.name = "new"\n assert orig.name == "original"\n assert copy.name == "copy"\n assert new.name == "new"\n\n def test_constructor_corner(self):\n arr = np.array([1, 2, 3, 4], dtype=object)\n index = RangeIndex(1, 5)\n assert index.values.dtype == np.int64\n expected = Index(arr).astype("int64")\n\n tm.assert_index_equal(index, expected, exact="equiv")\n\n # non-int raise Exception\n with pytest.raises(TypeError, match=r"Wrong type \<class 'str'\>"):\n RangeIndex("1", "10", "1")\n with pytest.raises(TypeError, match=r"Wrong type \<class 'float'\>"):\n RangeIndex(1.1, 10.2, 1.3)\n\n # invalid passed type\n with pytest.raises(\n ValueError,\n match="Incorrect `dtype` passed: expected signed integer, received float64",\n ):\n RangeIndex(1, 5, dtype="float64")\n | .venv\Lib\site-packages\pandas\tests\indexes\ranges\test_constructors.py | test_constructors.py | Python | 5,328 | 0.95 | 0.079268 | 0.044444 | node-utils | 261 | 2024-08-18T16:45:40.889975 | Apache-2.0 | true | ee3d5e00cc4884809e5fc53200aaf90d |
import numpy as np\nimport pytest\n\nfrom pandas import (\n Index,\n RangeIndex,\n)\nimport pandas._testing as tm\n\n\nclass TestGetIndexer:\n def test_get_indexer(self):\n index = RangeIndex(start=0, stop=20, step=2)\n target = RangeIndex(10)\n indexer = index.get_indexer(target)\n expected = np.array([0, -1, 1, -1, 2, -1, 3, -1, 4, -1], dtype=np.intp)\n tm.assert_numpy_array_equal(indexer, expected)\n\n def test_get_indexer_pad(self):\n index = RangeIndex(start=0, stop=20, step=2)\n target = RangeIndex(10)\n indexer = index.get_indexer(target, method="pad")\n expected = np.array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4], dtype=np.intp)\n tm.assert_numpy_array_equal(indexer, expected)\n\n def test_get_indexer_backfill(self):\n index = RangeIndex(start=0, stop=20, step=2)\n target = RangeIndex(10)\n indexer = index.get_indexer(target, method="backfill")\n expected = np.array([0, 1, 1, 2, 2, 3, 3, 4, 4, 5], dtype=np.intp)\n tm.assert_numpy_array_equal(indexer, expected)\n\n def test_get_indexer_limit(self):\n # GH#28631\n idx = RangeIndex(4)\n target = RangeIndex(6)\n result = idx.get_indexer(target, method="pad", limit=1)\n expected = np.array([0, 1, 2, 3, 3, -1], dtype=np.intp)\n tm.assert_numpy_array_equal(result, expected)\n\n @pytest.mark.parametrize("stop", [0, -1, -2])\n def test_get_indexer_decreasing(self, stop):\n # GH#28678\n index = RangeIndex(7, stop, -3)\n result = index.get_indexer(range(9))\n expected = np.array([-1, 2, -1, -1, 1, -1, -1, 0, -1], dtype=np.intp)\n tm.assert_numpy_array_equal(result, expected)\n\n\nclass TestTake:\n def test_take_preserve_name(self):\n index = RangeIndex(1, 5, name="foo")\n taken = index.take([3, 0, 1])\n assert index.name == taken.name\n\n def test_take_fill_value(self):\n # GH#12631\n idx = RangeIndex(1, 4, name="xxx")\n result = idx.take(np.array([1, 0, -1]))\n expected = Index([2, 1, 3], dtype=np.int64, name="xxx")\n tm.assert_index_equal(result, expected)\n\n # fill_value\n msg = "Unable to fill values because RangeIndex cannot contain NA"\n with pytest.raises(ValueError, match=msg):\n idx.take(np.array([1, 0, -1]), fill_value=True)\n\n # allow_fill=False\n result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True)\n expected = Index([2, 1, 3], dtype=np.int64, name="xxx")\n tm.assert_index_equal(result, expected)\n\n msg = "Unable to fill values because RangeIndex cannot contain NA"\n with pytest.raises(ValueError, match=msg):\n idx.take(np.array([1, 0, -2]), fill_value=True)\n with pytest.raises(ValueError, match=msg):\n idx.take(np.array([1, 0, -5]), fill_value=True)\n\n def test_take_raises_index_error(self):\n idx = RangeIndex(1, 4, name="xxx")\n\n msg = "index -5 is out of bounds for (axis 0 with )?size 3"\n with pytest.raises(IndexError, match=msg):\n idx.take(np.array([1, -5]))\n\n msg = "index -4 is out of bounds for (axis 0 with )?size 3"\n with pytest.raises(IndexError, match=msg):\n idx.take(np.array([1, -4]))\n\n # no errors\n result = idx.take(np.array([1, -3]))\n expected = Index([2, 1], dtype=np.int64, name="xxx")\n tm.assert_index_equal(result, expected)\n\n def test_take_accepts_empty_array(self):\n idx = RangeIndex(1, 4, name="foo")\n result = idx.take(np.array([]))\n expected = Index([], dtype=np.int64, name="foo")\n tm.assert_index_equal(result, expected)\n\n # empty index\n idx = RangeIndex(0, name="foo")\n result = idx.take(np.array([]))\n expected = Index([], dtype=np.int64, name="foo")\n tm.assert_index_equal(result, expected)\n\n def test_take_accepts_non_int64_array(self):\n idx = RangeIndex(1, 4, name="foo")\n result = idx.take(np.array([2, 1], dtype=np.uint32))\n expected = Index([3, 2], dtype=np.int64, name="foo")\n tm.assert_index_equal(result, expected)\n\n def test_take_when_index_has_step(self):\n idx = RangeIndex(1, 11, 3, name="foo") # [1, 4, 7, 10]\n result = idx.take(np.array([1, 0, -1, -4]))\n expected = Index([4, 1, 10, 1], dtype=np.int64, name="foo")\n tm.assert_index_equal(result, expected)\n\n def test_take_when_index_has_negative_step(self):\n idx = RangeIndex(11, -4, -2, name="foo") # [11, 9, 7, 5, 3, 1, -1, -3]\n result = idx.take(np.array([1, 0, -1, -8]))\n expected = Index([9, 11, -3, 11], dtype=np.int64, name="foo")\n tm.assert_index_equal(result, expected)\n\n\nclass TestWhere:\n def test_where_putmask_range_cast(self):\n # GH#43240\n idx = RangeIndex(0, 5, name="test")\n\n mask = np.array([True, True, False, False, False])\n result = idx.putmask(mask, 10)\n expected = Index([10, 10, 2, 3, 4], dtype=np.int64, name="test")\n tm.assert_index_equal(result, expected)\n\n result = idx.where(~mask, 10)\n tm.assert_index_equal(result, expected)\n | .venv\Lib\site-packages\pandas\tests\indexes\ranges\test_indexing.py | test_indexing.py | Python | 5,171 | 0.95 | 0.131387 | 0.072072 | python-kit | 860 | 2023-10-13T13:55:00.317237 | MIT | true | 3cd4e9c9224cf89d3a77e741bd371b52 |
import numpy as np\n\nfrom pandas import (\n Index,\n RangeIndex,\n)\nimport pandas._testing as tm\n\n\nclass TestJoin:\n def test_join_outer(self):\n # join with Index[int64]\n index = RangeIndex(start=0, stop=20, step=2)\n other = Index(np.arange(25, 14, -1, dtype=np.int64))\n\n res, lidx, ridx = index.join(other, how="outer", return_indexers=True)\n noidx_res = index.join(other, how="outer")\n tm.assert_index_equal(res, noidx_res)\n\n eres = Index(\n [0, 2, 4, 6, 8, 10, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]\n )\n elidx = np.array(\n [0, 1, 2, 3, 4, 5, 6, 7, -1, 8, -1, 9, -1, -1, -1, -1, -1, -1, -1],\n dtype=np.intp,\n )\n eridx = np.array(\n [-1, -1, -1, -1, -1, -1, -1, -1, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0],\n dtype=np.intp,\n )\n\n assert isinstance(res, Index) and res.dtype == np.dtype(np.int64)\n assert not isinstance(res, RangeIndex)\n tm.assert_index_equal(res, eres, exact=True)\n tm.assert_numpy_array_equal(lidx, elidx)\n tm.assert_numpy_array_equal(ridx, eridx)\n\n # join with RangeIndex\n other = RangeIndex(25, 14, -1)\n\n res, lidx, ridx = index.join(other, how="outer", return_indexers=True)\n noidx_res = index.join(other, how="outer")\n tm.assert_index_equal(res, noidx_res)\n\n assert isinstance(res, Index) and res.dtype == np.int64\n assert not isinstance(res, RangeIndex)\n tm.assert_index_equal(res, eres)\n tm.assert_numpy_array_equal(lidx, elidx)\n tm.assert_numpy_array_equal(ridx, eridx)\n\n def test_join_inner(self):\n # Join with non-RangeIndex\n index = RangeIndex(start=0, stop=20, step=2)\n other = Index(np.arange(25, 14, -1, dtype=np.int64))\n\n res, lidx, ridx = index.join(other, how="inner", return_indexers=True)\n\n # no guarantee of sortedness, so sort for comparison purposes\n ind = res.argsort()\n res = res.take(ind)\n lidx = lidx.take(ind)\n ridx = ridx.take(ind)\n\n eres = Index([16, 18])\n elidx = np.array([8, 9], dtype=np.intp)\n eridx = np.array([9, 7], dtype=np.intp)\n\n assert isinstance(res, Index) and res.dtype == np.int64\n tm.assert_index_equal(res, eres)\n tm.assert_numpy_array_equal(lidx, elidx)\n tm.assert_numpy_array_equal(ridx, eridx)\n\n # Join two RangeIndex\n other = RangeIndex(25, 14, -1)\n\n res, lidx, ridx = index.join(other, how="inner", return_indexers=True)\n\n assert isinstance(res, RangeIndex)\n tm.assert_index_equal(res, eres, exact="equiv")\n tm.assert_numpy_array_equal(lidx, elidx)\n tm.assert_numpy_array_equal(ridx, eridx)\n\n def test_join_left(self):\n # Join with Index[int64]\n index = RangeIndex(start=0, stop=20, step=2)\n other = Index(np.arange(25, 14, -1, dtype=np.int64))\n\n res, lidx, ridx = index.join(other, how="left", return_indexers=True)\n eres = index\n eridx = np.array([-1, -1, -1, -1, -1, -1, -1, -1, 9, 7], dtype=np.intp)\n\n assert isinstance(res, RangeIndex)\n tm.assert_index_equal(res, eres)\n assert lidx is None\n tm.assert_numpy_array_equal(ridx, eridx)\n\n # Join withRangeIndex\n other = Index(np.arange(25, 14, -1, dtype=np.int64))\n\n res, lidx, ridx = index.join(other, how="left", return_indexers=True)\n\n assert isinstance(res, RangeIndex)\n tm.assert_index_equal(res, eres)\n assert lidx is None\n tm.assert_numpy_array_equal(ridx, eridx)\n\n def test_join_right(self):\n # Join with Index[int64]\n index = RangeIndex(start=0, stop=20, step=2)\n other = Index(np.arange(25, 14, -1, dtype=np.int64))\n\n res, lidx, ridx = index.join(other, how="right", return_indexers=True)\n eres = other\n elidx = np.array([-1, -1, -1, -1, -1, -1, -1, 9, -1, 8, -1], dtype=np.intp)\n\n assert isinstance(other, Index) and other.dtype == np.int64\n tm.assert_index_equal(res, eres)\n tm.assert_numpy_array_equal(lidx, elidx)\n assert ridx is None\n\n # Join withRangeIndex\n other = RangeIndex(25, 14, -1)\n\n res, lidx, ridx = index.join(other, how="right", return_indexers=True)\n eres = other\n\n assert isinstance(other, RangeIndex)\n tm.assert_index_equal(res, eres)\n tm.assert_numpy_array_equal(lidx, elidx)\n assert ridx is None\n\n def test_join_non_int_index(self):\n index = RangeIndex(start=0, stop=20, step=2)\n other = Index([3, 6, 7, 8, 10], dtype=object)\n\n outer = index.join(other, how="outer")\n outer2 = other.join(index, how="outer")\n expected = Index([0, 2, 3, 4, 6, 7, 8, 10, 12, 14, 16, 18])\n tm.assert_index_equal(outer, outer2)\n tm.assert_index_equal(outer, expected)\n\n inner = index.join(other, how="inner")\n inner2 = other.join(index, how="inner")\n expected = Index([6, 8, 10])\n tm.assert_index_equal(inner, inner2)\n tm.assert_index_equal(inner, expected)\n\n left = index.join(other, how="left")\n tm.assert_index_equal(left, index.astype(object))\n\n left2 = other.join(index, how="left")\n tm.assert_index_equal(left2, other)\n\n right = index.join(other, how="right")\n tm.assert_index_equal(right, other)\n\n right2 = other.join(index, how="right")\n tm.assert_index_equal(right2, index.astype(object))\n\n def test_join_non_unique(self):\n index = RangeIndex(start=0, stop=20, step=2)\n other = Index([4, 4, 3, 3])\n\n res, lidx, ridx = index.join(other, return_indexers=True)\n\n eres = Index([0, 2, 4, 4, 6, 8, 10, 12, 14, 16, 18])\n elidx = np.array([0, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9], dtype=np.intp)\n eridx = np.array([-1, -1, 0, 1, -1, -1, -1, -1, -1, -1, -1], dtype=np.intp)\n\n tm.assert_index_equal(res, eres)\n tm.assert_numpy_array_equal(lidx, elidx)\n tm.assert_numpy_array_equal(ridx, eridx)\n\n def test_join_self(self, join_type):\n index = RangeIndex(start=0, stop=20, step=2)\n joined = index.join(index, how=join_type)\n assert index is joined\n | .venv\Lib\site-packages\pandas\tests\indexes\ranges\test_join.py | test_join.py | Python | 6,268 | 0.95 | 0.050847 | 0.066176 | awesome-app | 763 | 2024-10-28T14:26:07.988645 | Apache-2.0 | true | e3c9e191923e4a301e5e6a2f0d50defd |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.