SantoshGupta7
SantoshGupta7

Reputation: 6197

How to convert a multi-key dictionary to a pandas dataframe, where each key and value has its own column?

Say I have a dictionary that looks like this

mkd = {('aab', 'ccd', 'bbd'): 3, ('aeb', 'cfd', 'bfd'): 8, ('atb', 'cttd', 'bft'): 83}

How could I mad a pandas dataframe where each key and value has its own column.

I see there's a solution for creating a pandas df from here

Creating a panda DataFrame from dictionary with multiple keys and value (list) of different lengths

dataframe1 = pd.DataFrame(dict([(k,pd.Series(v)) for k,v in my_dict.iteritems()]))  

But the solution results in a muli-header

aab
ccd
bbd
3

Where as I am looking for an example row of this

        col1  col2  col3 col4
    0 'aab' 'ccd'  'bbd'     3

Upvotes: 4

Views: 1152

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150745

You can convert it to a series and then reset index:

pd.Series(mkd).reset_index()

Output:

  level_0 level_1 level_2   0
0     aab     ccd     bbd   3
1     aeb     cfd     bfd   8
2     atb    cttd     bft  83

Upvotes: 8

Related Questions