Home > Mobile >  convert dictionary containing nested list of lists to df
convert dictionary containing nested list of lists to df

Time:10-09

I have a dictionary containing what I think are called nested list of lists as shown below....

data = {'length': [[1633345896441, 101.25], [1633348822964, 101.67], [1633353200096, 102.32]], 'weight' : [[1633345896441, 7.09], [1633348822964, 7.44], [1633353200096, 7.51]]}

I am trying to convert to a single df as shown below....

             date   length    weight     
0    1633345896441  101.25      7.09   
1    1633348822964  101.67      7.44
2    1633353200096  102.32      7.51

However, I seem to be going in the wrong direction with my efforts so far...

k, v = list(data.items())[0]
df = pd.DataFrame(v).reset_index(drop=True)

Help much needed - please

CodePudding user response:

One approach:

import pandas as pd

data = {'length': [[1633345896441, 101.25], [1633348822964, 101.67], [1633353200096, 102.32]],
        'weight' : [[1633345896441, 7.09], [1633348822964, 7.44], [1633353200096, 7.51]]}

df = pd.DataFrame({k : dict(v) for k, v in data.items()}).rename_axis("date").reset_index()
print(df)

Output

            date  length  weight
0  1633345896441  101.25    7.09
1  1633348822964  101.67    7.44
2  1633353200096  102.32    7.51
  • Related