python 在NumPy中将dict转换为数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2224620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:06:48  来源:igfitidea点击:

Convert dict to array in NumPy

pythonarraysdictionarynumpy

提问by wheaties

I'd like to take a dictionary of a dictionary containing floats, indexed by ints and convert it into a numpy.array for use with the numpy library. Currently I'm manually converting the values into two arrays, one for the original indexes and the other for the values. While I've looked at numpy.asarraymy conclusion has been that I must be doing something wrong with it. Could anyone show an example of how to properly convert such a creation? Don't have to use numpy.asarray, anything will do.

我想获取包含浮点数的字典的字典,由整数索引,并将其转换为 numpy.array 以与 numpy 库一起使用。目前我正在手动将值转换为两个数组,一个用于原始索引,另一个用于值。虽然我看过numpy.asarray我的结论是我一定做错了什么。谁能举例说明如何正确转换这样的创作?不用用numpy.asarray,什么都行。

from collections import defaultdict
foo = defaultdict( lambda: defaultdict(float) )
#Then "foo" is populated by several
#routines reading results from a DB
#
#As an example
foo[ 7104 ][ 3 ] = 4.5
foo[ 203 ][ 1 ] = 3.2
foo[ 2 ][ 1 ] = 2.7

I'd like to have just a multi-dimensional array of floats, not an array of dicts.

我只想拥有一个多维浮点数组,而不是一个字典数组。

Edit:

编辑:

Sorry for the delay. Here is the code that I was using to create the first array object containing just the values:

抱歉耽搁了。这是我用来创建第一个只包含值的数组对象的代码:

storedArray = numpy.asarray( reduce( lambda x,y: x + y, (item.values() for item in storedMapping.values() ) ) )

I was hoping someone might know a magic bullet that could convert a dict of dict into an array.

我希望有人可能知道可以将 dict 的 dict 转换为数组的灵丹妙药。

回答by John La Rooy

You can calculate N and M like this

你可以这样计算 N 和 M

N=max(foo)+1
M=max(max(x) for x in foo.values())+1
fooarray = numpy.zeros((N, M))
for key1, row in foo.iteritems():
   for key2, value in row.iteritems():
       fooarray[key1, key2] = value 

There are various optionsfor sparse arrays. Eg,

稀疏数组有多种选择。例如,

import scipy.sparse
foosparse = scipy.sparse.lil_matrix((N, M))
for key1, row in foo.iteritems():
   for key2, value in row.iteritems():
       foosparse[(key1, key2)] = value 

回答by bayer

Say you have a NxM array, then I'd do the following:

假设您有一个 NxM 阵列,那么我会执行以下操作:

myarray = numpy.zeros((N, M))
for key1, row in mydict.iteritems():
   for key2, value in row.iteritems():
       myarray[key1, key2] = value