Create Pandas DataFrame from dictionary

Viewed 1601

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!

3 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]])

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

You can use numpy.concatenate and numpy.repeat:

import numpy as np

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

values = np.concatenate(list(d.values()))
lens = list(map(len, d.values()))

res = pd.DataFrame({0: np.repeat(list(d), lens),
                    1: values})

Result

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

This seems tougher than it should be, but remember you need to create arrays for each series / column. In essence, we need to repeat dictionary keys for series 0 and concatenate dictionary values for series 1.

Related