Home > OS >  Convert a dictionary to pandas dataframe
Convert a dictionary to pandas dataframe

Time:06-16

I have a dictionary in which values are odict_items:

{1: odict_items([('a', 0.0952), ('b', 14.583351), ('c', 120000), ('d', 6000)]),
 2: odict_items([('a', 0.098733336), ('b', 14.526156), ('c', 120000), ('d', 6000)])}

When I convert it to a dataframe the output is as follows:

df = pd.DataFrame(dict.values())

          0            1             2          3
0   (a, 0.0952) (b, 14.583351)  (c, 120000) (d, 6000)
1   (a, 0.0987) (b, 14.526156)  (c, 120000) (c, 6000)

But the desired output is as follows (first column is the key and the next columns are values in odict_items):

      a        b          c       d
1   0.0952  14.583351   120000  6000
2   0.0987  14.526156   120000  6000

Any help would be appreciated.

CodePudding user response:

You need to reconstruct valid dictionaries from the items:

pd.DataFrame.from_dict({k: dict(v) for k,v in dic.items()}, orient='index')

Output:

          a          b       c       d
1  0.095200  14.583351    6000     NaN
2  0.098733  14.526156  120000  6000.0

Used input:

from collections import OrderedDict
dic = {1: OrderedDict([('a', 0.0952), ('b', 14.583351), ('c', 120000), ('c', 6000)]).items(),
       2: OrderedDict([('a', 0.098733336), ('b', 14.526156), ('c', 120000), ('d', 6000)]).items()}
  • Related