I was curious if it were possible to use MultiIndexes, so I made an attempt. This may have its benefits if you want to specify levels. But simply following the pandas documentation example ( MultiIdex) I came up with an alternative solution.
First I created a dictionary of random data
s = {(1,2):"a", (4,5):"b", (1,5):"w", (2, 3):"z", (4,1):"p"}
Then I used pd.MultiIndex
to create a Hierarchical index from the dictionary's keys.
index = pd.MultiIndex.from_tuples(s.keys())
index
Out[3]:
MultiIndex(levels=[[1, 2, 4], [1, 2, 3, 5]],
labels=[[0, 2, 2, 1, 0], [1, 3, 0, 2, 3]])
Then, I pass the dictionary's values directly to a pandas Series, and explicitly set the index to be the MultiIndex object I created above.
pd.Series(s.values(), index=index)
Out[4]:
1 2 a
4 5 b
1 p
2 3 z
1 5 w
dtype: object
Lastly, I reset the index to get the solution requested by OP
pd.Series(s.values(), index=index).reset_index()
Out[5]:
level_0 level_1 0
0 1 2 a
1 4 5 b
2 4 1 p
3 2 3 z
4 1 5 w
This was a bit more involved, so @ayhan's answer may still be preferable, but I think this gives you an idea of what pandas may be doing in the background. Or at least give anyone the opportunity to tinker with pandas' mechanics a bit more.