Bryan Stafford
Bryan Stafford

Reputation: 301

Adding nested dictionaries as a row into Multi-Indexed DataFrame

I would like to create a 3-level Multi-Indexed pandas DataFrame much like the one found in this Stack Overflow question but I would like to be able to add new data after the DataFrame has been created.

Here is the Multi-Indexed DataFrame from the linked post. I have renamed the lower column levels for clarity.

AA           BB
   A     B     A     B
   a  b  a  b  a  b  a  b
0  2  2  2  2  2  2  2  2
1  3  3  3  3  3  3  3  3
2  4  4  4  4  4  4  4  4
3  5  5  5  5  5  5  5  5
4  6  6  6  6  6  6  6  6

The data that I will be passing to it will be a nested dictionary in the following form:

dictionary = {'AA': {'A': {'a': [9],
                           'b': [8]},
                     'B': {'a': [6],
                           'b': [2]}},
              'BB': {'A': {'a': [3],
                           'b': [8]},
                     'B': {'a': [1],
                           'b': [3]}}}

Any idea how I can accomplish this?

Upvotes: 0

Views: 65

Answers (1)

EFT
EFT

Reputation: 2369

You could transform the new data into a dataframe as described in the linked post, then use pd.concat to combine it with the original dataframe.

Using your example:

df
Out[127]: 
  AA          BB         
   A     B     A     B   
   a  b  a  b  a  b  a  b
0  2  2  2  2  2  2  2  2
1  3  3  3  3  3  3  3  3
2  4  4  4  4  4  4  4  4
3  5  5  5  5  5  5  5  5
4  6  6  6  6  6  6  6  6

newrow
Out[129]: 
  AA          BB         
   A     B     A     B   
   a  b  a  b  a  b  a  b
0  9  8  6  2  3  8  1  3

pd.concat([df, newrow])
Out[130]: 
  AA          BB         
   A     B     A     B   
   a  b  a  b  a  b  a  b
0  2  2  2  2  2  2  2  2
1  3  3  3  3  3  3  3  3
2  4  4  4  4  4  4  4  4
3  5  5  5  5  5  5  5  5
4  6  6  6  6  6  6  6  6
0  9  8  6  2  3  8  1  3

Upvotes: 1

Related Questions