Home > Software engineering >  Python Pandas: Create DataFrame from dictionary that has values of list of lists
Python Pandas: Create DataFrame from dictionary that has values of list of lists

Time:03-21

I have dictionary like below:

dict = {key_1:[[1, 2], [3, 4]], key_2:[[1, 2], [3, 4]]}

I want to convert this to a dataframe like below:

      colum_1 column_2 
key_1   1       2 
key_1   3       4 
key_2   1       2 
key_2   3       4 

What is the most efficient way to do this. Thanks for help=)

CodePudding user response:

Let us try comprehension to unnest the key-val pairs

pd.DataFrame((k, *l) for k, v in d.items() for l in v).set_index(0)

       1  2
0          
key_1  1  2
key_1  3  4
key_2  1  2
key_2  3  4

CodePudding user response:

IIUC, you could use:

cols = ['col1', 'col2']
df = pd.DataFrame({k: zip(*v) for k,v in d.items()}, index=cols).T.explode(cols)

output:

      col1 col2
key_1    1    2
key_1    3    4
key_2    1    2
key_2    3    4
  • Related