Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Pandas DataFrame from dictionary

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!

like image 982
Bubble Bubble Bubble Gut Avatar asked Dec 14 '22 15:12

Bubble Bubble Bubble Gut


2 Answers

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]])
like image 109
dursun Avatar answered Dec 28 '22 18:12

dursun


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
like image 26
BENY Avatar answered Dec 28 '22 20:12

BENY