简体   繁体   中英

Convert a dictionary to pandas dataframe

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.

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()}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM