With below code I tried to insert a new row label (two name-levels) but it appears that MultiIndex.insert() does not work according to the printed output. User xyzjayne mentions here "MultiIndex is immutable". Then why is there MultiIndex.insert and/or how to use MultiIndex.insert properly in below case to get desired result?
NOT an option:
add ('D', '9') to
labelstuple list before MultiIndexing. Thislabelsis general, has a default list order and is used a few times elsewhere in different settings. And thus prior to the creation of a DataFrame.
Versions :pandas 0.25.1 py37ha925a31_0
Desired result:
row_labels MultiIndex([('A', '1'),
('A', '2'),
('B', '3'),
('B', '4'),
('C', '5'),
('C', '6'),
('D', '9'), # inserted row label ('D', '9')
('D', '7'),
('D', '8')],
names=['group', 'subgroup'])
My code:
import pandas as pd
labels = {'A' : ['1', '2'],
'B' : ['3', '4'],
'C' : ['5', '6'],
'D' : ['7', '8']}
tpl = []
for g, sg in labels.items():
for s in sg:
tpl.append((g, s))
row_labels = pd.MultiIndex.from_tuples(tpl, names=['group', 'subgroup'])
print ('row_labels', row_labels)
i = row_labels.get_locs(('D',))
print ('\nD is found at row(s): ', i)
# add row at position 6
row_labels.insert(6, (('D', '9')))
# check for added label
print ('\nrow_labels', row_labels)
My current output:
row_labels MultiIndex([('A', '1'),
('A', '2'),
('B', '3'),
('B', '4'),
('C', '5'),
('C', '6'),
('D', '7'),
('D', '8')],
names=['group', 'subgroup'])
D is found at row(s): [6 7]
row_labels MultiIndex([('A', '1'),
('A', '2'),
('B', '3'),
('B', '4'),
('C', '5'),
('C', '6'),
('D', '7'),
('D', '8')],
names=['group', 'subgroup'])