将一个二维字典转换为NumPy矩阵。

21
我有一个巨大的字典,像这样:
d[id1][id2] = value

例子:

books["auth1"]["humor"] = 20
books["auth1"]["action"] = 30
books["auth2"]["comedy"] = 20
每个 "auth" 键都可以与任何一组 "genres" 相关联。键控项目的值是他们写的书籍数量。 现在我想将它转换为矩阵形式...类似于:
                    "humor"       "action"        "comedy"
      "auth1"         20            30               0
      "auth2"          0            0                20

我该如何做到这一点? 谢谢


首先遍历字典,然后找到行数和列数。接着在迭代过程中将每个条目转换为定义的向量。然后在另一个迭代中通过id1将其与它们的向量关联起来。 - frazman
你只是想像那样打印出来吗?为什么需要放入一个numpy矩阵中? - Paul Seeb
@PaulSeeb:不不,实际上我想稍后对这个矩阵执行SVD。 - frazman
3个回答

27

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数组? - tommy.carstensen
对于变长字典值,请使用DataFrame.from_dict(books, orient='index').fillna(0)来防止ValueError - interpolack

10

使用列表推导式将字典转换为列表或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]]。 - frazman
@Fraz:啊,所以每个作者字典的键数量都不规则。让我来编辑一下。 - Joel Cornett

0

在2018年,我认为Pandas 0.22支持这个开箱即用。 具体来说,请查看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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接