Home > Enterprise >  Convert dict with lists in values to Pandas dataframe
Convert dict with lists in values to Pandas dataframe

Time:09-19

I have a dictionary with the following keys and values

my_dict={'1':{'name':'one',
              'f_10':[1,10,20,30],
              'f_20':[1,20,40,60]},
        '2':{'name':'two',
              'f_10':[2,12,22,32],
              'f_20':[2,22,42,62]}}

How do I convert it to a Pandas DataFrame that will look like:

name      name      f_10           f_20
1         one       [1,10,20,30]   [1,10,20,60]
2         two       [2,12,22,32]   [2,22,42,62]

The lists need to be considered in one column based on the key, if I try to concat these get converted to separate rows in the data frame.

CodePudding user response:

Simply use orient=index when importing your data using from_dict:

df = pd.DataFrame.from_dict(my_dict, orient = 'index')

This returns:

    name    f_10    f_20
1   one     [1, 10, 20, 30]     [1, 20, 40, 60]
2   two     [2, 12, 22, 32]     [2, 22, 42, 62]

CodePudding user response:

I would parse that dictionary to DataFrame and have it transposed. For example,

pd.DataFrame(my_dict).T

Result

    name  f_10              f_20
1   one   [1, 10, 20, 30]   [1, 20, 40, 60]
2   two   [2, 12, 22, 32]   [2, 22, 42, 62]
  • Related