简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM