Drop indexed coordinates associated with coordinates in coords_to_drop. This will raise an error in case it corrupts any passed index and its coordinate variables.
(
coords_to_drop: set[Hashable], coords: Coordinates
)
| 1160 | |
| 1161 | |
| 1162 | def drop_indexed_coords( |
| 1163 | coords_to_drop: set[Hashable], coords: Coordinates |
| 1164 | ) -> Coordinates: |
| 1165 | """Drop indexed coordinates associated with coordinates in coords_to_drop. |
| 1166 | |
| 1167 | This will raise an error in case it corrupts any passed index and its |
| 1168 | coordinate variables. |
| 1169 | |
| 1170 | """ |
| 1171 | new_variables = dict(coords.variables) |
| 1172 | new_indexes = dict(coords.xindexes) |
| 1173 | |
| 1174 | for idx, idx_coords in coords.xindexes.group_by_index(): |
| 1175 | idx_drop_coords = set(idx_coords) & coords_to_drop |
| 1176 | |
| 1177 | # special case for pandas multi-index: still allow but deprecate |
| 1178 | # dropping only its dimension coordinate. |
| 1179 | # TODO: remove when removing PandasMultiIndex's dimension coordinate. |
| 1180 | if isinstance(idx, PandasMultiIndex) and idx_drop_coords == {idx.dim}: |
| 1181 | idx_drop_coords.update(idx.index.names) |
| 1182 | emit_user_level_warning( |
| 1183 | f"updating coordinate {idx.dim!r}, which is a PandasMultiIndex, would leave " |
| 1184 | f"the multi-index level coordinates {list(idx.index.names)!r} in an inconsistent state. " |
| 1185 | f"This will raise an error in the future. Use `.drop_vars({list(idx_coords)!r})` " |
| 1186 | "to drop the coordinates' values before assigning new coordinate values.", |
| 1187 | FutureWarning, |
| 1188 | ) |
| 1189 | |
| 1190 | elif idx_drop_coords and len(idx_drop_coords) != len(idx_coords): |
| 1191 | idx_drop_coords_str = ", ".join(f"{k!r}" for k in idx_drop_coords) |
| 1192 | idx_coords_str = ", ".join(f"{k!r}" for k in idx_coords) |
| 1193 | raise ValueError( |
| 1194 | f"cannot drop or update coordinate(s) {idx_drop_coords_str}, which would corrupt " |
| 1195 | f"the following index built from coordinates {idx_coords_str}:\n" |
| 1196 | f"{idx}" |
| 1197 | ) |
| 1198 | |
| 1199 | for k in idx_drop_coords: |
| 1200 | del new_variables[k] |
| 1201 | del new_indexes[k] |
| 1202 | |
| 1203 | return Coordinates._construct_direct(coords=new_variables, indexes=new_indexes) |
| 1204 | |
| 1205 | |
| 1206 | def assert_coordinate_consistent(obj: T_Xarray, coords: Mapping[Any, Variable]) -> None: |
no test coverage detected
searching dependent graphs…