【问题标题】:converting a 2d dictionary to a numpy matrix将二维字典转换为 numpy 矩阵
【发布时间】:2012-05-24 07:32:07
【问题描述】:

我有一本像这样的大字典:

d[id1][id2] = value

示例:

books["auth1"]["humor"] = 20
books["auth1"]["action"] = 30
books["auth2"]["comedy"] = 20

等等..

每个“auth”键都可以有任何一组与之关联的“流派”。键项的值是他们写的书的数量。

现在我想要的是将它转换为矩阵的形式......类似于:

                    "humor"       "action"        "comedy"
      "auth1"         20            30               0
      "auth2"          0            0                20

我该怎么做? 谢谢

【问题讨论】:

  • 首先遍历字典,然后找到行数和列数.. 之后我迭代将每个条目转换为定义的向量.. 然后在另一个迭代中通过 id1.. 关联它与他们的向量
  • 您只想这样打印出来吗?为什么需要进入一个numpy矩阵
  • @PaulSeeb: 不不.. 实际上我想稍后执行这个矩阵的 svd..

标签: python numpy


【解决方案1】:

使用列表推导将 dict 转换为列表列表和/或 numpy 数组:

np.array([[books[author][genre] for genre in sorted(books[author])] for author in sorted(books)])

编辑

显然,您在每个子词典中都有不规则数量的键。列出所有类型:

genres = ['humor', 'action', 'comedy']

然后以正常方式遍历字典:

list_of_lists = []
for author_name, author in sorted(books.items()):
    titles = []
    for genre in genres:
        try:
            titles.append(author[genre])
        except KeyError:
            titles.append(0)
    list_of_lists.append(titles)

books_array = numpy.array(list_of_lists)

基本上,我试图将genres 中每个键的值附加到列表中。如果密钥不存在,则会引发错误。我发现了错误,并将 0 附加到列表中。

【讨论】:

  • 嗨,这给了我:array([[20, 30], [50]], dtype=object) 但我期待的是 [[20, 30, 0],[0, 0,50]]
  • @Fraz:啊,所以每个作者字典都有不规则数量的键。让我编辑。
【解决方案2】:

pandas这个做得很好:

books = {}
books["auth1"] = {}
books["auth2"] = {}
books["auth1"]["humor"] = 20
books["auth1"]["action"] = 30
books["auth2"]["comedy"] = 20

from pandas import *

df = DataFrame(books).T.fillna(0)

输出是:

       action  comedy  humor
auth1      30       0     20
auth2       0      20      0

【讨论】:

  • @HYRY 可以使用 pandas DataFrame 作为 matplotlib.pcolor 的输入来创建热图吗?还是必须先转换为 numpy 数组?
  • 在可变长度字典值的情况下,使用DataFrame.from_dict(books, orient='index').fillna(0)代替ValueError
【解决方案3】:

2018 年,我认为 Pandas 0.22 支持这个out of the box。 具体请查看DataFramefrom_dict类方法。

books = {}
books["auth1"] = {}
books["auth2"] = {}
books["auth1"]["humor"] = 20
books["auth1"]["action"] = 30
books["auth2"]["comedy"] = 20

pd.DataFrame.from_dict(books, orient='columns', dtype=None)

【讨论】:

    猜你喜欢
    • 2016-02-02
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-05
    • 1970-01-01
    • 2013-05-26
    • 1970-01-01
    相关资源
    最近更新 更多