Nested dictionary for MultiIndex pandas DataFrame (3 levels)

I would like to do the equivalent of this for a 3rd level nested dictionary

Nested dictionary in multi-index framework, where dictionary keys are column labels

+6
source share
1 answer

Using an example of a three-story dict

In [1]: import pandas as pd In [2]: dictionary = {'A': {'a': {1: [2,3,4,5,6], ...: 2: [2,3,4,5,6]}, ...: 'b': {1: [2,3,4,5,6], ...: 2: [2,3,4,5,6]}}, ...: 'B': {'a': {1: [2,3,4,5,6], ...: 2: [2,3,4,5,6]}, ...: 'b': {1: [2,3,4,5,6], ...: 2: [2,3,4,5,6]}}} 

And the following understanding of a dictionary based on one of the question related to

 In [3]: reform = {(level1_key, level2_key, level3_key): values ...: for level1_key, level2_dict in dictionary.items() ...: for level2_key, level3_dict in level2_dict.items() ...: for level3_key, values in level3_dict.items()} 

What gives

 In [4]: reform Out[4]: {('A', 'a', 1): [2, 3, 4, 5, 6], ('A', 'a', 2): [2, 3, 4, 5, 6], ('A', 'b', 1): [2, 3, 4, 5, 6], ('A', 'b', 2): [2, 3, 4, 5, 6], ('B', 'a', 1): [2, 3, 4, 5, 6], ('B', 'a', 2): [2, 3, 4, 5, 6], ('B', 'b', 1): [2, 3, 4, 5, 6], ('B', 'b', 2): [2, 3, 4, 5, 6]} 

For pandas DataFrame

 In [5]: pd.DataFrame(reform) Out[5]: AB abab 1 2 1 2 1 2 1 2 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 In [6]: df = pd.DataFrame(reform).T Out[6]: 0 1 2 3 4 A a 1 2 3 4 5 6 2 2 3 4 5 6 b 1 2 3 4 5 6 2 2 3 4 5 6 B a 1 2 3 4 5 6 2 2 3 4 5 6 b 1 2 3 4 5 6 2 2 3 4 5 6 

As you can see, you can easily increase the number of levels by adding another line for understanding and a new key for the tuple.

Bonus: Add Names to Indexes

 In [7]: names=['level1', 'level2', 'level3'] In [8]: df.index.set_names(names, inplace=True) In [9]: df Out[9]: 0 1 2 3 4 level1 level2 level3 A a 1 2 3 4 5 6 2 2 3 4 5 6 b 1 2 3 4 5 6 2 2 3 4 5 6 B a 1 2 3 4 5 6 2 2 3 4 5 6 b 1 2 3 4 5 6 2 2 3 4 5 6 
+5
source

Source: https://habr.com/ru/post/987698/


All Articles