'multi-dimensional dictionary to dataframe python
dict_abc = {'A': [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
'B': [[4, 4, 4], [2, 2, 3],],
'C': [[4, 6, 0]]
}
I would like to convert this to a dataframe in the form
| x | y | z |
A 1 2 3
A 4 5 6
A 7 8 9
B 4 4 4
B 2 2 3
C 4 6 0
Solution 1:[1]
One option, read as Series, explode and convert again to DataFrame:
s = pd.Series(dict_abc).explode()
df = pd.DataFrame(s.to_list(), index=s.index, columns=['x', 'y', 'z'])
output:
x y y
A 1 2 3
A 4 5 6
A 7 8 9
B 4 4 4
B 2 2 3
C 4 6 0
Solution 2:[2]
Use:
In [2471]: x = pd.DataFrame.from_dict(dict_abc, orient='index').stack()
In [2478]: df = pd.DataFrame(x.tolist(), index=x.index, columns=['x', 'y', 'z']).droplevel(1)
In [2479]: df
Out[2479]:
x y z
A 1 2 3
A 4 5 6
A 7 8 9
B 4 4 4
B 2 2 3
C 4 6 0
Solution 3:[3]
Using itertools.chain:
from itertools import chain
df = pd.DataFrame(itertools.chain.from_iterable(dict_abc.values()),
columns=['x', 'y', 'z'],
index=chain.from_iterable([k]*len(v) for k,v in dict_abc.items()))
output:
x y z
A 1 2 3
A 4 5 6
A 7 8 9
B 4 4 4
B 2 2 3
C 4 6 0
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mozway |
| Solution 2 | Mayank Porwal |
| Solution 3 | mozway |
