I was trying to convert a dictionary of {'a': [1, 2, 3], 'b': [4, 5]}
into:
0 | 1 |
|:-----------|------------:|
| a | 1 |
| a | 2 |
| a | 3 |
| b | 4 |
| b | 5 |
But haven't found any way to achieve that without modifying the dictionary itself. Is there an easier way to do that? Any help will be really appreciated! Thank you!
you can expand the dict into list of tuples and then convert into df as follows;
ddd = {'a': [1, 2, 3], 'b': [4, 5]}
df = pd.DataFrame([(k,v) for k in ddd for v in ddd[k]])
Using pd.DataFrame.from_dict
pd.DataFrame.from_dict(d,'index').stack().reset_index(level=0)
Out[194]:
level_0 0
0 a 1.0
1 a 2.0
2 a 3.0
0 b 4.0
1 b 5.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With