I have a dictionary of the following form:
{'x': 1, 'y': 2, 'z':{'a': 3, 'b': 4}, 'w': {'a': 5, 'b': 6}}
I want to create a df like this:
What is the best way to achieve this?
I have a dictionary of the following form:
{'x': 1, 'y': 2, 'z':{'a': 3, 'b': 4}, 'w': {'a': 5, 'b': 6}}
I want to create a df like this:
What is the best way to achieve this?
If you have only 2 levels:
import pandas as pd
d = {'x': 1, 'y': 2, 'z':{'a': 3, 'b': 4}, 'w': {'a': 5, 'b': 6}}
data = {}
for k1, v1 in d.items():
if isinstance(v1, dict):
for k2, v2 in v1.items():
data[(k1, k2)] = v2
else:
data[(k1, '')] = v1
df = pd.DataFrame([data.values()], columns=data)
Output:
>>> df
x y z w # index, level 1
a b a b # index, level 2
0 1 2 3 4 5 6 # values