How can i convert a python dictionary with tuple keys to a pandas multi Index data frame?

Viewed 484

I have a python dictionary with tuples as keys ex:

dict={('m1',17):4,('m1',12):2,('m1',1):5,('m3',11):4,('m3',17):15}

I want to convert it into a pandas data frame like this:

m1 17 4
   12 2
   1  5
m3 11 4
   17 15

I've tried the following:

df1=pd.DataFrame(dict)
df2=pd.DataFrame.from_dict(dict)
df3=pd.Series(dict.values(),index=pd.MultiIndex.from_tuples(dict.keys(), names=['site','id'])

However, nothing works. (I also need to name the index columns and value column)

2 Answers

This works:

from pandas import DataFrame, MultiIndex

d = {('m1', 17): 4, ('m1', 12): 2, ('m1', 1): 5, ('m3', 11): 4, ('m3', 17): 15}
data = DataFrame(
    data={'column_name': list(d.values())}, 
    index=MultiIndex.from_tuples(tuples=d.keys(), names=['site', 'id'])
)

Try with Series

s = pd.Series(d)
Out[198]: 
m1  17     4
    12     2
    1      5
m3  11     4
    17    15
dtype: int64
Related