Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pandas

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

like image 959
SantoshGupta7 Avatar asked Sep 03 '25 17:09

SantoshGupta7


1 Answers

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
like image 66
Quang Hoang Avatar answered Sep 05 '25 07:09

Quang Hoang