Home > database >  multi-dimensional dictionary to dataframe python
multi-dimensional dictionary to dataframe python

Time:03-24

dict_abc = {'A': [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
         'B': [[4, 4, 4], [2, 2, 3],],
         'C': [[4, 6, 0]]
        }

I would like to convert this to a dataframe in the form

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

CodePudding user response:

One option, read as Series, explode and convert again to DataFrame:

s = pd.Series(dict_abc).explode()
df = pd.DataFrame(s.to_list(), index=s.index, columns=['x', 'y', 'z'])

output:

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

CodePudding user response:

Use:

In [2471]: x = pd.DataFrame.from_dict(dict_abc, orient='index').stack()
In [2478]: df = pd.DataFrame(x.tolist(), index=x.index, columns=['x', 'y', 'z']).droplevel(1)

In [2479]: df
Out[2479]: 
   x  y  z
A  1  2  3
A  4  5  6
A  7  8  9
B  4  4  4
B  2  2  3
C  4  6  0

CodePudding user response:

Using itertools.chain:

from itertools import chain

df = pd.DataFrame(itertools.chain.from_iterable(dict_abc.values()),
                  columns=['x', 'y', 'z'],
                  index=chain.from_iterable([k]*len(v) for k,v in dict_abc.items()))

output:

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