Home > Blockchain >  Convert dictionary (with list elements as values) to dataframe
Convert dictionary (with list elements as values) to dataframe

Time:01-26

I have a dictionary (keys are string and values are lists) like below:

d = {
    '5/8': [[12, 15], [15, 18]],
    '12/19': [[2, 3]],
    '20/22': [[13, 18], [28, 22], [17, 110]]}

I need to convert it to a dataframe in a way that keys be in a column and repeated based on the number of list elements in corresponding values and also keys be separated into two other columns like below:

     id    x    y
  '5/8'   12   15
  '5/8'   15   18
'12/19'    2    3
'20/22'   13   18
'20/22'   28   22
'20/22'   17   110

What is the most efficient way to create this dataframe?

CodePudding user response:

Use a list comprehension.

df = pd.DataFrame(
    [(k, x, y) for k,v in d.items() for x,y in v],
    columns=['id', 'x', 'y'])
df
      id   x    y
0    5/8  12   15
1    5/8  15   18
2  12/19   2    3
3  20/22  13   18
4  20/22  28   22
5  20/22  17  110
  • Related