Skip to content Skip to sidebar Skip to footer

Adding New Multiindex Level

I have a DataFrame: d = pd.DataFrame({'i1': ['A', 'B', 'C', 'D', 'E'], 'i2': ['I', 'II', 'III', 'IV', 'V'], 'val': ['lol1', 'lol2', 'lol3', 'lol

Solution 1:

Create list of tuples by values from MultiIndex, then use DataFrame.reindex with MultiIndex.from_tuples:

vals = [5, 10, 15]
tups = [x + (i,) for x in d.index for i in vals]
d = d.reindex(pd.MultiIndex.from_tuples(tups, names=['i1','i2','i3']))
print (d)
            val
i1 i2  i3      
A  I   5   lol1
       10  lol1
       15  lol1
B  II  5   lol2
       10  lol2
       15  lol2
C  III 5   lol3
       10  lol3
       15  lol3
D  IV  5   lol4
       10  lol4
       15  lol4
E  V   5   lol5
       10  lol5
       15  lol5

Post a Comment for "Adding New Multiindex Level"