|
4 | 4 |
|
5 | 5 | from __future__ import annotations |
6 | 6 |
|
7 | | -from typing import TYPE_CHECKING, Any, Generic, TypeVar |
| 7 | +from typing import TYPE_CHECKING, Any, Callable, Generic, TypeVar |
8 | 8 |
|
9 | 9 | import pandas as pd |
10 | 10 |
|
11 | | -from pandas_openscm.index_manipulation import ensure_is_multiindex |
| 11 | +from pandas_openscm.index_manipulation import ensure_is_multiindex, update_levels |
12 | 12 |
|
13 | 13 | if TYPE_CHECKING: |
14 | 14 | # Hmm this is somehow not correct. |
@@ -72,3 +72,73 @@ def eim(self) -> pd.MultiIndex: |
72 | 72 | this is a no-op (although the value of copy is respected). |
73 | 73 | """ |
74 | 74 | return self.ensure_is_multiindex() |
| 75 | + |
| 76 | + def update_index_levels( |
| 77 | + self, |
| 78 | + updates: dict[Any, Callable[[Any], Any]], |
| 79 | + remove_unused_levels: bool = True, |
| 80 | + ) -> pd.MultiIndex: |
| 81 | + """ |
| 82 | + Update the levels |
| 83 | +
|
| 84 | + Parameters |
| 85 | + ---------- |
| 86 | + updates |
| 87 | + Updates to apply |
| 88 | +
|
| 89 | + Each key is the level to which the updates will be applied. |
| 90 | + Each value is a function which updates the level to its new values. |
| 91 | +
|
| 92 | + remove_unused_levels |
| 93 | + Remove unused levels before applying the update |
| 94 | +
|
| 95 | + Specifically, call |
| 96 | + [pd.MultiIndex.remove_unused_levels][pandas.MultiIndex.remove_unused_levels]. |
| 97 | +
|
| 98 | + This avoids trying to update levels that aren't being used. |
| 99 | +
|
| 100 | + Returns |
| 101 | + ------- |
| 102 | + : |
| 103 | + [pd.MultiIndex][pandas.MultiIndex] with updates applied |
| 104 | + """ |
| 105 | + return update_levels( |
| 106 | + self._index, |
| 107 | + updates=updates, |
| 108 | + remove_unused_levels=remove_unused_levels, |
| 109 | + ) |
| 110 | + |
| 111 | + def update_levels_from_other( |
| 112 | + self, |
| 113 | + updates: dict[Any, Callable[[Any], Any]], |
| 114 | + remove_unused_levels: bool = True, |
| 115 | + ) -> pd.MultiIndex: |
| 116 | + """ |
| 117 | + Update the levels |
| 118 | +
|
| 119 | + Parameters |
| 120 | + ---------- |
| 121 | + updates |
| 122 | + Updates to apply |
| 123 | +
|
| 124 | + Each key is the level to which the updates will be applied. |
| 125 | + Each value is a function which updates the level to its new values. |
| 126 | +
|
| 127 | + remove_unused_levels |
| 128 | + Remove unused levels before applying the update |
| 129 | +
|
| 130 | + Specifically, call |
| 131 | + [pd.MultiIndex.remove_unused_levels][pandas.MultiIndex.remove_unused_levels]. |
| 132 | +
|
| 133 | + This avoids trying to update levels that aren't being used. |
| 134 | +
|
| 135 | + Returns |
| 136 | + ------- |
| 137 | + : |
| 138 | + [pd.MultiIndex][pandas.MultiIndex] with updates applied |
| 139 | + """ |
| 140 | + return update_levels( |
| 141 | + self._index, |
| 142 | + updates=updates, |
| 143 | + remove_unused_levels=remove_unused_levels, |
| 144 | + ) |
0 commit comments