Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Changing the Values of a Multi-Index Dataframe

I have a multi-index dataframe that is set up as follows:

index = pd.MultiIndex.from_product([['A','B','C'], ['x','y', 'z']])
multi_index = pd.DataFrame(np.nan, index=np.arange(10), columns=index)

Which produces the following output:

A           B           C        
    x   y   z   x   y   z   x   y   z
0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
1 NaN NaN NaN NaN NaN NaN NaN NaN NaN
2 NaN NaN NaN NaN NaN NaN NaN NaN NaN
3 NaN NaN NaN NaN NaN NaN NaN NaN NaN
4 NaN NaN NaN NaN NaN NaN NaN NaN NaN
5 NaN NaN NaN NaN NaN NaN NaN NaN NaN
6 NaN NaN NaN NaN NaN NaN NaN NaN NaN
7 NaN NaN NaN NaN NaN NaN NaN NaN NaN
8 NaN NaN NaN NaN NaN NaN NaN NaN NaN
9 NaN NaN NaN NaN NaN NaN NaN NaN NaN

I am trying to fill the values of the multi-index data frame with values. As a toy example, what I’ve tried to do is change the value of [‘A’,’x’,0] as follows:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

multi_index['A']['x'].loc[0] = 65.2

However, I receive a ‘SettingWithCopyWarning’, which makes sense to me. I’ve also tried

multi_index['A'].iloc[[1],0] = 65.2

and received the same warning.

Is there a way one can change the values of a multi-index dataframe on a entry-by-entry basis? I.E changing the 0th index of [‘A’,’x’]?

>Solution :

Try:

multi_index.loc[0, ('A', 'x')] = 65.2

You can use tuples with loc for index labelling to access your multiindex columns or rows.

Or you can use iloc like this using integer index position selection, for example 2 here is the third column:

multi_index.iloc[0, 2] = 70.3

Output:

      A             B           C        
      x   y     z   x   y   z   x   y   z
0  65.2 NaN  70.3 NaN NaN NaN NaN NaN NaN
1   NaN NaN   NaN NaN NaN NaN NaN NaN NaN
2   NaN NaN   NaN NaN NaN NaN NaN NaN NaN
3   NaN NaN   NaN NaN NaN NaN NaN NaN NaN
4   NaN NaN   NaN NaN NaN NaN NaN NaN NaN
5   NaN NaN   NaN NaN NaN NaN NaN NaN NaN
6   NaN NaN   NaN NaN NaN NaN NaN NaN NaN
7   NaN NaN   NaN NaN NaN NaN NaN NaN NaN
8   NaN NaN   NaN NaN NaN NaN NaN NaN NaN
9   NaN NaN   NaN NaN NaN NaN NaN NaN NaN
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading