Ehsan Mehralian
Ehsan Mehralian

Reputation: 345

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.

Upvotes: 11

Views: 10961

Answers (2)

user3483203
user3483203

Reputation: 51165

Use the splat operator in a comprehension to produce your dataframe:

pd.DataFrame([k, *v] for k, v in d.items())

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

If you don't mind having index as one of your column names, simply transpose and reset_index:

pd.DataFrame(d).T.reset_index()

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

Finally, although it's rather ugly, the most performant option I could find on very large dictionaries is the following:

pd.DataFrame(list(d.values()), index=list(d.keys())).reset_index()

Upvotes: 5

xyzjayne
xyzjayne

Reputation: 1387

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.

Upvotes: 12

Related Questions