pandas_openscm.index_manipulation#
Manipulation of the index of data
Functions:
| Name | Description |
|---|---|
convert_index_to_category_index |
Convert the index's values to categories |
create_level_from_collection |
Create new level and corresponding codes. |
create_new_level_and_codes_by_mapping |
Create a new level and associated codes by mapping an existing level |
create_new_level_and_codes_by_mapping_multiple |
Create a new level and associated codes by mapping existing levels |
ensure_index_is_multiindex |
Ensure that the index of a pandas object is a pd.MultiIndex |
ensure_is_multiindex |
Ensure that an index is a pd.MultiIndex |
set_index_levels_func |
Set the index levels of a pd.DataFrame |
set_levels |
Set the levels of a MultiIndex to the provided values |
unify_index_levels |
Unify the levels on two indexes |
unify_index_levels_check_index_types |
Unify the levels on two indexes |
update_index_from_candidates |
Update the index of data to align with the candidate columns as much as possible |
update_index_levels_from_other_func |
Update the index levels based on other levels of a pandas object |
update_index_levels_func |
Update the index levels of a pandas object |
update_levels |
Update the levels of a pd.MultiIndex |
update_levels_from_other |
Update levels based on other levels in a pd.MultiIndex |
convert_index_to_category_index #
Convert the index's values to categories
This can save a lot of memory and improve the speed of processing. However, it comes with some pitfalls. For a nice discussion of some of them, see this article.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pandas_obj
|
P
|
Object whose index we want to change to categorical. |
required |
Returns:
| Type | Description |
|---|---|
P
|
A new object with the same data as |
Source code in src/pandas_openscm/index_manipulation.py
create_level_from_collection #
create_level_from_collection(
level: str, value: Collection[Any]
) -> tuple[Index[Any], NDArray[integer[Any]]]
Create new level and corresponding codes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
level
|
str
|
Name of the level to create |
required |
value
|
Collection[Any]
|
Values to use to create the level |
required |
Returns:
| Type | Description |
|---|---|
tuple[Index[Any], NDArray[integer[Any]]]
|
New level and corresponding codes |
Source code in src/pandas_openscm/index_manipulation.py
create_new_level_and_codes_by_mapping #
create_new_level_and_codes_by_mapping(
ini: MultiIndex,
level_to_create_from: str,
mapper: Callable[[Any], Any]
| dict[Any, Any]
| Series[Any],
) -> tuple[Index[Any], NDArray[integer[Any]]]
Create a new level and associated codes by mapping an existing level
This is a thin function intended for internal use to handle some slightly tricky logic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ini
|
MultiIndex
|
Input index |
required |
level_to_create_from
|
str
|
Level to create the new level from |
required |
mapper
|
Callable[[Any], Any] | dict[Any, Any] | Series[Any]
|
Function to use to map existing levels to new levels |
required |
Returns:
| Name | Type | Description |
|---|---|---|
new_level |
Index[Any]
|
New level |
new_codes |
NDArray[integer[Any]]
|
New codes |
Source code in src/pandas_openscm/index_manipulation.py
create_new_level_and_codes_by_mapping_multiple #
create_new_level_and_codes_by_mapping_multiple(
ini: MultiIndex,
levels_to_create_from: tuple[str, ...],
mapper: Callable[[Any], Any]
| dict[Any, Any]
| Series[Any],
) -> tuple[Index[Any], NDArray[integer[Any]]]
Create a new level and associated codes by mapping existing levels
This is a thin function intended for internal use to handle some slightly tricky logic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ini
|
MultiIndex
|
Input index |
required |
levels_to_create_from
|
tuple[str, ...]
|
Levels to create the new level from |
required |
mapper
|
Callable[[Any], Any] | dict[Any, Any] | Series[Any]
|
Function to use to map existing levels to new levels |
required |
Returns:
| Name | Type | Description |
|---|---|---|
new_level |
Index[Any]
|
New level |
new_codes |
NDArray[integer[Any]]
|
New codes |
Source code in src/pandas_openscm/index_manipulation.py
ensure_index_is_multiindex #
ensure_index_is_multiindex(
pandas_obj: P, copy: bool = True
) -> P
Ensure that the index of a pandas object is a pd.MultiIndex
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pandas_obj
|
P
|
Object whose index we want to ensure is a pd.MultiIndex |
required |
copy
|
bool
|
Should we copy |
True
|
Returns:
| Type | Description |
|---|---|
P
|
If the index was already a pd.MultiIndex, this is a no-op (although the value of copy is respected). |
Source code in src/pandas_openscm/index_manipulation.py
ensure_is_multiindex #
ensure_is_multiindex(
index: Index[Any] | MultiIndex,
) -> MultiIndex
Ensure that an index is a pd.MultiIndex
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
Index[Any] | MultiIndex
|
Index to check |
required |
Returns:
| Type | Description |
|---|---|
MultiIndex
|
Index, cast to pd.MultiIndex if needed |
Source code in src/pandas_openscm/index_manipulation.py
set_index_levels_func #
set_index_levels_func(
pobj: P,
levels_to_set: dict[str, Any | Collection[Any]],
copy: bool = True,
) -> P
Set the index levels of a pd.DataFrame
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pobj
|
P
|
Supported pandas object to update |
required |
levels_to_set
|
dict[str, Any | Collection[Any]]
|
Mapping of level names to values to set |
required |
copy
|
bool
|
Should |
True
|
Returns:
| Type | Description |
|---|---|
P
|
|
Source code in src/pandas_openscm/index_manipulation.py
set_levels #
set_levels(
ini: MultiIndex,
levels_to_set: dict[str, Any | Collection[Any]],
) -> MultiIndex
Set the levels of a MultiIndex to the provided values
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ini
|
MultiIndex
|
Input MultiIndex |
required |
levels_to_set
|
dict[str, Any | Collection[Any]]
|
Mapping of level names to values to set. If values is of type |
required |
Returns:
| Type | Description |
|---|---|
MultiIndex
|
New MultiIndex with the levels set to the provided values |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If the length of the values is a collection that is not equal to the length of the index |
Examples:
>>> start = pd.MultiIndex.from_tuples(
... [
... ("sa", "ma", "v1", "kg"),
... ("sb", "ma", "v2", "m"),
... ("sa", "mb", "v1", "kg"),
... ("sa", "mb", "v2", "m"),
... ],
... names=["scenario", "model", "variable", "unit"],
... )
>>> start
MultiIndex([('sa', 'ma', 'v1', 'kg'),
('sb', 'ma', 'v2', 'm'),
('sa', 'mb', 'v1', 'kg'),
('sa', 'mb', 'v2', 'm')],
names=['scenario', 'model', 'variable', 'unit'])
>>>
>>> # Set a new level with a single string
>>> set_levels(
... start,
... {"new_variable": "xyz"},
... )
MultiIndex([('sa', 'ma', 'v1', 'kg', 'xyz'),
('sb', 'ma', 'v2', 'm', 'xyz'),
('sa', 'mb', 'v1', 'kg', 'xyz'),
('sa', 'mb', 'v2', 'm', 'xyz')],
names=['scenario', 'model', 'variable', 'unit', 'new_variable'])
>>>
>>> # Replace a level with a collection
>>> set_levels(
... start,
... {"new_variable": [1, 2, 3, 4]},
... )
MultiIndex([('sa', 'ma', 'v1', 'kg', 1),
('sb', 'ma', 'v2', 'm', 2),
('sa', 'mb', 'v1', 'kg', 3),
('sa', 'mb', 'v2', 'm', 4)],
names=['scenario', 'model', 'variable', 'unit', 'new_variable'])
>>>
>>> # Replace a level with a single value and add a new level
>>> set_levels(
... start,
... {"model": "new_model", "new_variable": ["xyz", "xyz", "x", "y"]},
... )
MultiIndex([('sa', 'new_model', 'v1', 'kg', 'xyz'),
('sb', 'new_model', 'v2', 'm', 'xyz'),
('sa', 'new_model', 'v1', 'kg', 'x'),
('sa', 'new_model', 'v2', 'm', 'y')],
names=['scenario', 'model', 'variable', 'unit', 'new_variable'])
Source code in src/pandas_openscm/index_manipulation.py
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 | |
unify_index_levels #
unify_index_levels(
left: MultiIndex, right: MultiIndex
) -> tuple[MultiIndex, MultiIndex]
Unify the levels on two indexes
The levels are unified by simply adding NaN to any level in either left or right
that is not in the level of the other index.
This is differnt to pd.DataFrame.align. pd.DataFrame.align will fill missing values with values from the other index if it can. We don't want that here. We want any non-aligned levels to be filled with NaN.
The implementation also allows this to be performed on indexes directly (avoiding casting to a DataFrame and avoiding paying the price of aligning everything else or creating a bunch of NaN that we just drop straight away).
The indexes are returned with the levels from left first,
then the levels from right.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
left
|
MultiIndex
|
First index to unify |
required |
right
|
MultiIndex
|
Second index to unify |
required |
Returns:
| Name | Type | Description |
|---|---|---|
left_aligned |
MultiIndex
|
Left after alignment |
right_aligned |
MultiIndex
|
Right after alignment |
Examples:
>>> import pandas as pd
>>>
>>> idx_a = pd.MultiIndex.from_tuples(
... [
... (1, 2, 3),
... (4, 5, 6),
... ],
... names=["a", "b", "c"],
... )
>>> idx_b = pd.MultiIndex.from_tuples(
... [
... (7, 8),
... (10, 11),
... ],
... names=["a", "b"],
... )
>>> unified_a, unified_b = unify_index_levels(idx_a, idx_b)
>>> unified_a
MultiIndex([(1, 2, 3),
(4, 5, 6)],
names=['a', 'b', 'c'])
>>>
>>> unified_b
MultiIndex([( 7, 8, nan),
(10, 11, nan)],
names=['a', 'b', 'c'])
>>>
>>> # Also fine if b has swapped levels
>>> idx_b = pd.MultiIndex.from_tuples(
... [
... (7, 8),
... (10, 11),
... ],
... names=["b", "a"],
... )
>>> unified_a, unified_b = unify_index_levels(idx_a, idx_b)
>>> unified_a
MultiIndex([(1, 2, 3),
(4, 5, 6)],
names=['a', 'b', 'c'])
>>>
>>> unified_b
MultiIndex([( 8, 7, nan),
(11, 10, nan)],
names=['a', 'b', 'c'])
>>>
>>> # Also works if a is 'inside' b
>>> idx_a = pd.MultiIndex.from_tuples(
... [
... (7, 8),
... (10, 11),
... ],
... names=["a", "b"],
... )
>>> idx_b = pd.MultiIndex.from_tuples(
... [
... (1, 2, 3),
... (4, 5, 6),
... ],
... names=["a", "b", "c"],
... )
>>> unified_a, unified_b = unify_index_levels(idx_a, idx_b)
>>> unified_a
MultiIndex([( 7, 8, nan),
(10, 11, nan)],
names=['a', 'b', 'c'])
>>>
>>> unified_b
MultiIndex([(1, 2, 3),
(4, 5, 6)],
names=['a', 'b', 'c'])
>>>
>>> # But, be a bit careful, this is now sensitive to a's column order
>>> idx_a = pd.MultiIndex.from_tuples(
... [
... (7, 8),
... (10, 11),
... ],
... names=["b", "a"],
... )
>>> idx_b = pd.MultiIndex.from_tuples(
... [
... (1, 2, 3),
... (4, 5, 6),
... ],
... names=["a", "b", "c"],
... )
>>> unified_a, unified_b = unify_index_levels(idx_a, idx_b)
>>> # Note that the names are `['b', 'a', 'c']` in the output
>>> unified_a
MultiIndex([( 7, 8, nan),
(10, 11, nan)],
names=['b', 'a', 'c'])
>>>
>>> unified_b
MultiIndex([(2, 1, 3),
(5, 4, 6)],
names=['b', 'a', 'c'])
Source code in src/pandas_openscm/index_manipulation.py
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 | |
unify_index_levels_check_index_types #
unify_index_levels_check_index_types(
left: Index[Any], right: Index[Any]
) -> tuple[MultiIndex, MultiIndex]
Unify the levels on two indexes
This is just a thin wrapper around unify_index_levels that checks the the inputs are both pd.MultiIndex before unifying the indices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
left
|
Index[Any]
|
First index to unify |
required |
right
|
Index[Any]
|
Second index to unify |
required |
Returns:
| Name | Type | Description |
|---|---|---|
left_aligned |
MultiIndex
|
Left after alignment |
right_aligned |
MultiIndex
|
Right after alignment |
Source code in src/pandas_openscm/index_manipulation.py
update_index_from_candidates #
Update the index of data to align with the candidate columns as much as possible
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indf
|
DataFrame
|
Data of which to update the index |
required |
candidates
|
Iterable[Hashable]
|
Candidate columns to use to create the updated index |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
All columns of |
Notes
This overwrites any existing index of indf
so you will only want to use this function
when you're sure that there isn't anything of interest
already in the index of indf.
Source code in src/pandas_openscm/index_manipulation.py
update_index_levels_from_other_func #
update_index_levels_from_other_func(
pobj: P,
update_sources: dict[
Any,
tuple[
Any,
Callable[[Any], Any]
| dict[Any, Any]
| Series[Any],
]
| tuple[
tuple[Any, ...],
Callable[[tuple[Any, ...]], Any]
| dict[tuple[Any, ...], Any]
| Series[Any],
],
],
copy: bool = True,
remove_unused_levels: bool = True,
) -> P
Update the index levels based on other levels of a pandas object
If the level to be updated doesn't exist, it is created.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pobj
|
P
|
Supported pandas object to update |
required |
update_sources
|
dict[Any, tuple[Any, Callable[[Any], Any] | dict[Any, Any] | Series[Any]] | tuple[tuple[Any, ...], Callable[[tuple[Any, ...]], Any] | dict[tuple[Any, ...], Any] | Series[Any]]]
|
Updates to apply to Each key is the level to which the updates will be applied (or the level that will be created if it doesn't already exist). There are two options for the values. The first is used when only one level is used to update the 'target level'. In this case, each value is a tuple of which the first element is the level to use to generate the values (the 'source level') and the second is mapper of the form used by pd.Index.map which will be applied to the source level to update/create the level of interest. Each value is a tuple of which the first element is the level or levels (if a tuple) to use to generate the values (the 'source level') and the second is mapper of the form used by pd.Index.map which will be applied to the source level to update/create the level of interest. |
required |
copy
|
bool
|
Should |
True
|
remove_unused_levels
|
bool
|
Call This avoids trying to update levels that aren't being used. |
True
|
Returns:
| Type | Description |
|---|---|
P
|
|
Source code in src/pandas_openscm/index_manipulation.py
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 | |
update_index_levels_func #
update_index_levels_func(
pobj: P,
updates: Mapping[
Any,
Callable[[Any], Any] | dict[Any, Any] | Series[Any],
],
copy: bool = True,
remove_unused_levels: bool = True,
) -> P
Update the index levels of a pandas object
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pobj
|
P
|
Supported pandas object to update |
required |
updates
|
Mapping[Any, Callable[[Any], Any] | dict[Any, Any] | Series[Any]]
|
Updates to apply to Each key is the index level to which the updates will be applied. Each value is a function which updates the levels to their new values. |
required |
copy
|
bool
|
Should |
True
|
remove_unused_levels
|
bool
|
Call This avoids trying to update levels that aren't being used. |
True
|
Returns:
| Type | Description |
|---|---|
P
|
|
Source code in src/pandas_openscm/index_manipulation.py
update_levels #
update_levels(
ini: MultiIndex,
updates: Mapping[
Any,
Callable[[Any], Any] | dict[Any, Any] | Series[Any],
],
remove_unused_levels: bool = True,
) -> MultiIndex
Update the levels of a pd.MultiIndex
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ini
|
MultiIndex
|
Input index |
required |
updates
|
Mapping[Any, Callable[[Any], Any] | dict[Any, Any] | Series[Any]]
|
Updates to apply Each key is the level to which the updates will be applied. Each value is a mapper of the form used by pd.Index.map. |
required |
remove_unused_levels
|
bool
|
Call This avoids trying to update levels that aren't being used. |
True
|
Returns:
| Type | Description |
|---|---|
MultiIndex
|
|
Raises:
| Type | Description |
|---|---|
KeyError
|
A level in |
Examples:
>>> start = pd.MultiIndex.from_tuples(
... [
... ("sa", "ma", "v1", "kg"),
... ("sb", "ma", "v2", "m"),
... ("sa", "mb", "v1", "kg"),
... ("sa", "mb", "v2", "m"),
... ],
... names=["scenario", "model", "variable", "unit"],
... )
>>> start
MultiIndex([('sa', 'ma', 'v1', 'kg'),
('sb', 'ma', 'v2', 'm'),
('sa', 'mb', 'v1', 'kg'),
('sa', 'mb', 'v2', 'm')],
names=['scenario', 'model', 'variable', 'unit'])
>>>
>>> update_levels(
... start,
... {"model": lambda x: f"model {x}", "scenario": lambda x: f"scenario {x}"},
... )
MultiIndex([('scenario sa', 'model ma', 'v1', 'kg'),
('scenario sb', 'model ma', 'v2', 'm'),
('scenario sa', 'model mb', 'v1', 'kg'),
('scenario sa', 'model mb', 'v2', 'm')],
names=['scenario', 'model', 'variable', 'unit'])
>>>
>>> update_levels(
... start,
... {"variable": {"v1": "variable one", "v2": "variable two"}},
... )
MultiIndex([('sa', 'ma', 'variable one', 'kg'),
('sb', 'ma', 'variable two', 'm'),
('sa', 'mb', 'variable one', 'kg'),
('sa', 'mb', 'variable two', 'm')],
names=['scenario', 'model', 'variable', 'unit'])
Source code in src/pandas_openscm/index_manipulation.py
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 | |
update_levels_from_other #
update_levels_from_other(
ini: MultiIndex,
update_sources: dict[
Any,
tuple[
Any,
Callable[[Any], Any]
| dict[Any, Any]
| Series[Any],
]
| tuple[
tuple[Any, ...],
Callable[[tuple[Any, ...]], Any]
| dict[tuple[Any, ...], Any]
| Series[Any],
],
],
remove_unused_levels: bool = True,
) -> MultiIndex
Update levels based on other levels in a pd.MultiIndex
If the level to be updated doesn't exist, it is created.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ini
|
MultiIndex
|
Input index |
required |
update_sources
|
dict[Any, tuple[Any, Callable[[Any], Any] | dict[Any, Any] | Series[Any]] | tuple[tuple[Any, ...], Callable[[tuple[Any, ...]], Any] | dict[tuple[Any, ...], Any] | Series[Any]]]
|
Updates to apply and their source levels Each key is the level to which the updates will be applied (or the level that will be created if it doesn't already exist). There are two options for the values. The first is used when only one level is used to update the 'target level'. In this case, each value is a tuple of which the first element is the level to use to generate the values (the 'source level') and the second is mapper of the form used by pd.Index.map which will be applied to the source level to update/create the level of interest. Each value is a tuple of which the first element is the level or levels (if a tuple) to use to generate the values (the 'source level') and the second is mapper of the form used by pd.Index.map which will be applied to the source level to update/create the level of interest. |
required |
remove_unused_levels
|
bool
|
Call This avoids trying to update based on levels that aren't being used. |
True
|
Returns:
| Type | Description |
|---|---|
MultiIndex
|
|
Raises:
| Type | Description |
|---|---|
KeyError
|
A source level in |
Examples:
>>> start = pd.MultiIndex.from_tuples(
... [
... ("sa", "ma", "v1", "kg"),
... ("sb", "ma", "v2", "m"),
... ("sa", "mb", "v1", "kg"),
... ("sa", "mb", "v2", "m"),
... ],
... names=["scenario", "model", "variable", "unit"],
... )
>>> start
MultiIndex([('sa', 'ma', 'v1', 'kg'),
('sb', 'ma', 'v2', 'm'),
('sa', 'mb', 'v1', 'kg'),
('sa', 'mb', 'v2', 'm')],
names=['scenario', 'model', 'variable', 'unit'])
>>>
>>> # Create a new level based on an existing level
>>> update_levels_from_other(
... start,
... {
... "unit squared": ("unit", lambda x: f"{x}**2"),
... "class": ("model", {"ma": "delta", "mb": "gamma"}),
... },
... )
MultiIndex([('sa', 'ma', 'v1', 'kg', 'kg**2', 'delta'),
('sb', 'ma', 'v2', 'm', 'm**2', 'delta'),
('sa', 'mb', 'v1', 'kg', 'kg**2', 'gamma'),
('sa', 'mb', 'v2', 'm', 'm**2', 'gamma')],
names=['scenario', 'model', 'variable', 'unit', 'unit squared', 'class'])
>>>
>>> # Update an existing level based on another level
>>> update_levels_from_other(
... start,
... {
... "unit": ("variable", {"v1": "g", "v2": "km"}),
... "model": ("scenario", lambda x: f"model {x}"),
... },
... )
MultiIndex([('sa', 'model sa', 'v1', 'g'),
('sb', 'model sb', 'v2', 'km'),
('sa', 'model sa', 'v1', 'g'),
('sa', 'model sa', 'v2', 'km')],
names=['scenario', 'model', 'variable', 'unit'])
>>>
>>> # Create a new level based on multiple existing levels
>>> update_levels_from_other(
... start,
... {
... "model || scenario": (("model", "scenario"), lambda x: " || ".join(x)),
... },
... )
MultiIndex([('sa', 'ma', 'v1', 'kg', 'sa || ma'),
('sb', 'ma', 'v2', 'm', 'sb || ma'),
('sa', 'mb', 'v1', 'kg', 'sa || mb'),
('sa', 'mb', 'v2', 'm', 'sa || mb')],
names=['scenario', 'model', 'variable', 'unit', 'model || scenario'])
>>>
>>> # Both at the same time
>>> update_levels_from_other(
... start,
... {
... "title": ("scenario", lambda x: x.capitalize()),
... "unit": ("unit", {"v1": "g", "v2": "km"}),
... },
... )
MultiIndex([('sa', 'ma', 'v1', nan, 'Sa'),
('sb', 'ma', 'v2', nan, 'Sb'),
('sa', 'mb', 'v1', nan, 'Sa'),
('sa', 'mb', 'v2', nan, 'Sa')],
names=['scenario', 'model', 'variable', 'unit', 'title'])
>>>
>>> # Setting with a range of different methods
>>> update_levels_from_other(
... start,
... {
... # callable
... "y-label": (("variable", "unit"), lambda x: f"{x[0]} ({x[1]})"),
... # dict
... "title": ("scenario", {"sa": "Scenario A", "sb": "Delta"}),
... # pd.Series
... "Source": (
... "model",
... pd.Series(["Internal", "External"], index=["ma", "mb"]),
... ),
... },
... )
MultiIndex([('sa', 'ma', 'v1', 'kg', 'v1 (kg)', 'Scenario A', 'Internal'),
('sb', 'ma', 'v2', 'm', 'v2 (m)', 'Delta', 'Internal'),
('sa', 'mb', 'v1', 'kg', 'v1 (kg)', 'Scenario A', 'External'),
('sa', 'mb', 'v2', 'm', 'v2 (m)', 'Scenario A', 'External')],
names=['scenario', 'model', 'variable', 'unit', 'y-label', 'title', 'Source'])
Source code in src/pandas_openscm/index_manipulation.py
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 | |