(self)
| 4022 | ds.reorder_levels(x=["level_1", "level_2"]) |
| 4023 | |
| 4024 | def test_set_xindex(self) -> None: |
| 4025 | ds = Dataset( |
| 4026 | coords={"foo": ("x", ["a", "a", "b", "b"]), "bar": ("x", [0, 1, 2, 3])} |
| 4027 | ) |
| 4028 | |
| 4029 | actual = ds.set_xindex("foo") |
| 4030 | expected = ds.set_index(x="foo").rename_vars(x="foo") |
| 4031 | assert_identical(actual, expected, check_default_indexes=False) |
| 4032 | |
| 4033 | actual_mindex = ds.set_xindex(["foo", "bar"]) |
| 4034 | expected_mindex = ds.set_index(x=["foo", "bar"]) |
| 4035 | assert_identical(actual_mindex, expected_mindex) |
| 4036 | |
| 4037 | class NotAnIndex: ... |
| 4038 | |
| 4039 | with pytest.raises(TypeError, match=r".*not a subclass of xarray.Index"): |
| 4040 | ds.set_xindex("foo", NotAnIndex) # type: ignore[arg-type] |
| 4041 | |
| 4042 | with pytest.raises(ValueError, match="those variables don't exist"): |
| 4043 | ds.set_xindex("not_a_coordinate", PandasIndex) |
| 4044 | |
| 4045 | ds["data_var"] = ("x", [1, 2, 3, 4]) |
| 4046 | |
| 4047 | with pytest.raises(ValueError, match="those variables are data variables"): |
| 4048 | ds.set_xindex("data_var", PandasIndex) |
| 4049 | |
| 4050 | ds = Dataset(coords={"x": ("x", [0, 1, 2, 3])}) |
| 4051 | |
| 4052 | # With drop_existing=True, it should succeed |
| 4053 | result = ds.set_xindex("x", PandasIndex) |
| 4054 | assert "x" in result.xindexes |
| 4055 | assert isinstance(result.xindexes["x"], PandasIndex) |
| 4056 | |
| 4057 | class CustomIndex(PandasIndex): |
| 4058 | pass |
| 4059 | |
| 4060 | result_custom = ds.set_xindex("x", CustomIndex) |
| 4061 | assert "x" in result_custom.xindexes |
| 4062 | assert isinstance(result_custom.xindexes["x"], CustomIndex) |
| 4063 | |
| 4064 | # Verify the result is equivalent to drop_indexes + set_xindex |
| 4065 | expected = ds.drop_indexes("x").set_xindex("x", CustomIndex) |
| 4066 | assert_identical(result_custom, expected) |
| 4067 | |
| 4068 | def test_set_xindex_options(self) -> None: |
| 4069 | ds = Dataset(coords={"foo": ("x", ["a", "a", "b", "b"])}) |
nothing calls this directly
no test coverage detected