Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Python dict of Arrays into a dataframe

I have a dictionary of arrays like the following:

d = {'a': [1,2], 'b': [3,4], 'c': [5,6]}

I want to create a pandas dataframe like this:

   0      1      2
0  a      1      2
1  b      3      4
2  c      5      6

I wrote the following code:

pd.DataFrame(list(d.items()))

which returns:

   0    1      
0  a  [1,2]      
1  b  [3,4]      
2  c  [5,6]    

Do you know how can I achieve my goal?!

Thank you in advance.

like image 650
Ehsan Mehralian Avatar asked Dec 23 '22 05:12

Ehsan Mehralian


1 Answers

Pandas allows you to do this in a straightforward fashion:

pd.DataFrame.from_dict(d,orient = 'index')
>>      0   1
    a   1   2
    b   3   4
    c   5   6

pd.DataFrame.from_dict(d,orient = 'index').reset_index() gives you what you are looking for.

like image 82
xyzjayne Avatar answered Dec 25 '22 20:12

xyzjayne