Skip to content

Commit 1447886

Browse files
author
cloudboat
committed
REF: Simplify tuple construction in MultiIndex.insert_level
1 parent 79e04b6 commit 1447886

File tree

1 file changed

+32
-6
lines changed

1 file changed

+32
-6
lines changed

pandas/core/indexes/multi.py

Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2711,6 +2711,36 @@ def reorder_levels(self, order) -> MultiIndex:
27112711
return result
27122712

27132713
def insert_level(self, position: int, value, name=None):
2714+
"""
2715+
Insert a new level at the specified position in the MultiIndex.
2716+
2717+
Parameters
2718+
----------
2719+
position : int
2720+
The position at which to insert the new level (0-based).
2721+
value : scalar or array-like
2722+
Value(s) to use for the new level. If scalar, broadcast to all items.
2723+
If array-like, length must match the length of the index.
2724+
name : object, optional
2725+
Name for the new level.
2726+
2727+
Returns
2728+
-------
2729+
MultiIndex
2730+
New MultiIndex with the inserted level.
2731+
2732+
Examples
2733+
--------
2734+
>>> idx = pd.MultiIndex.from_tuples([("A", 1), ("B", 2)])
2735+
>>> idx.insert_level(0, "new_value")
2736+
MultiIndex([('new_value', 'A', 1), ('new_value', 'B', 2)], ...)
2737+
2738+
>>> idx.insert_level(1, ["X", "Y"])
2739+
MultiIndex([('A', 'X', 1), ('B', 'Y', 2)], ...)
2740+
2741+
>>> idx.insert_level(0, "new_val", name="new_level")
2742+
MultiIndex([('new_val', 'A', 1), ('new_val', 'B', 2)], ...)
2743+
"""
27142744
if not isinstance(position, int):
27152745
raise TypeError("position must be an integer")
27162746

@@ -2725,13 +2755,9 @@ def insert_level(self, position: int, value, name=None):
27252755
raise ValueError("Length of values must match length of index")
27262756

27272757
new_tuples = []
2758+
27282759
for i, tup in enumerate(self):
2729-
if position == 0:
2730-
new_tuple = (value[i],) + tup
2731-
elif position == len(tup):
2732-
new_tuple = tup + (value[i],)
2733-
else:
2734-
new_tuple = tup[:position] + (value[i],) + tup[position:]
2760+
new_tuple = tup[:position] + (value[i],) + tup[position:]
27352761
new_tuples.append(new_tuple)
27362762

27372763
new_names = self.names[:position] + [name] + self.names[position:]

0 commit comments

Comments
 (0)