'How to manipulate the value of a pandas multiindex on a specific level?

Given a dataframe with row and column multiindex, how would you copy a row index "object" and manipulate a specific index value on a chosen level? Ultimately I would like to add a new row to the dataframe with this manipulated index.

Taking this dataframe df as an example:

col_index = pd.MultiIndex.from_product([['A','B'], [1,2,3,4]], names=['cInd1', 'cInd2'])
row_index = pd.MultiIndex.from_arrays([['2010','2011','2009'],['a','r','t'],[45,34,35]], names=["rInd1", "rInd2", 'rInd3'])

df = pd.DataFrame(data=None, index=row_index, columns=col_index)
df

cInd1                A                   B               
cInd2                1    2    3    4    1    2    3    4
rInd1 rInd2 rInd3                                        
2010  a     45     NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
2011  r     34     NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
2009  t     35     NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
                      

I would like to take the index of the first row, manipulate the "rInd2" value and use this index to insert another row.

Pseudo code would be something like this:

#Get Index
idx = df.index[0]
#Manipulate Value
idx[1] = "L" #or idx["rInd2"]

#Make new row with new index
df.loc[idx, slice(None)] = None

The desired output would look like this:

cInd1                A                   B               
cInd2                1    2    3    4    1    2    3    4
rInd1 rInd2 rInd3                                        
2010  a     45     NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
2011  r     34     NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
2009  t     35     NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
2010  L     45     NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN

What would be the most efficient way to achieve this?

Is there a way to do the same procedure with column index?

Thanks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source