dictionary with list values as multi index dataframe

Viewed 87

I want to get a multi index data frame from the following dictionaries :

d = {'a' : [1,2,3], 'b' : [4,5], 'c': [7,8]}

Tried pd.DataFrame.from_dict(d, orient='index') with no luck

The keys should be the index first level and the value the second level of the multi index, the desired output would be :

a     1
      2
      3

b     4
      5

c     7
      8
2 Answers

You can use the explode function from a Pandas Series

pd.Series({'a': [1,2,3], 'b' : [4,5], 'c': [7,8]}).explode()

will return

a    1
a    2
a    3
b    4
b    5
c    7
c    8

with some help from itertools

import pandas as pd
from itertools import chain, zip_longest

idx = chain.from_iterable([zip_longest(k, v, fillvalue=k) for k,v in d.items()])
pd.MultiIndex.from_tuples(idx)

MultiIndex([('a', 1),
            ('a', 2),
            ('a', 3),
            ('b', 4),
            ('b', 5),
            ('c', 7),
            ('c', 8)],
           )
Related