将字典转换为Numpy数组 [英] Convert Dictionary to Numpy array

查看:1756
本文介绍了将字典转换为Numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试转换字典

{0: {0: 173, 1: 342, 2: 666, 3: 506, 4: 94},
 1: {0: 13, 1: 2171, 2: 1915, 3: 3075, 4: 630},
 2: {0: 0, 1: 265, 2: 5036, 3: 508, 4: 11},
 3: {0: 0, 1: 3229, 2: 2388, 3: 3649, 4: 193},
 4: {0: 3, 1: 151, 2: 591, 3: 1629, 4: 410}}

到numpy数组

array([[ 173,  342,  666,  506,   94],
       [  13, 2171, 1915, 3075,  630],
       [   0,  265, 5036,  508,   11],
       [   0, 3229, 2388, 3649,  193],
       [   3,  151,  591, 1629,  410]])

任何想法如何有效地做到这一点?

Any ideas how to do it efficiently?

推荐答案

在这里不可避免地需要Python级别的循环,因此您可以使用列表推导:

A Python-level loop is unavoidable here, so you can use a list comprehension:

res = np.array([list(item.values()) for item in d.values()])

# array([[ 173,  342,  666,  506,   94],
#        [  13, 2171, 1915, 3075,  630],
#        [   0,  265, 5036,  508,   11],
#        [   0, 3229, 2388, 3649,  193],
#        [   3,  151,  591, 1629,  410]])

根据@FHTMitchell的评论,这假设您的字典项(内部和外部)已正确排序.字典在3.6中作为CPython实现的详细信息进行了插入排序,在3.7+中正式进行了排序.

As per @FHTMitchell's comment, this assumes your dictionary items (inner and outer) are ordered appropriately. Dictionaries are insertion ordered in 3.6 as a CPython implementation detail, and officially in 3.7+.

定义内部外字典顺序的一种方法是通过 operator.itemgetter :

One way to define an order for inner and outer dictionaries is via operator.itemgetter:

getter = itemgetter(*range(5))
res = np.array([getter(item) for item in getter(d)])

这种解决方案不依赖于输入字典的顺序.

Such a solution does not depend on the order of your input dictionary.

这篇关于将字典转换为Numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆