Create MultiIndex pandas DataFrame from dictionary with tuple keys
I would create a Series
using MultiIndex.from_tuples
and then unstack
it.
keys, values = zip(*counter.items())
idx = pd.MultiIndex.from_tuples(keys)
pd.Series(values, index=idx).unstack(-1, fill_value=0)
b d
a 5 2
c 0 7
Using DataFrame
constructor with stack
:
pd.DataFrame(counter, index=[0]).stack().loc[0].T
b d
a 5.0 2.0
c NaN 7.0
Using Series
with unstack
pd.Series(d).unstack(fill_value=0)
Out[708]:
b d
a 5 2
c 0 7
d={('a', 'b') : 5,
('c', 'd') : 7,
('a', 'd') : 2}