将词典转换为熊猫数据框

发布于 2025-02-07 19:15:40 字数 702 浏览 0 评论 0原文

我有一个字典,其中值为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)])}

当我将其转换为dataframe时,输出如下:

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)

)所需的输出如下(第一列是密钥,下一列是ODICT_ITEMS中的值):

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

任何帮助都将不胜感激。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无名指的心愿 2025-02-14 19:15:40

您需要从项目中重建有效词典:

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

输出:

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

二手输入:

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

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()}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文