如何将python dict转换为3D numpy数组?

时间:2016-04-12 11:47:25

标签: python numpy

我有一个带有n_keys的python dict,其中每个值都是一个2D数组(dim1,dim2)。 我想把它转换成一个3D numpy数组(dim1,dim2,n_keys)。 如果没有很多嵌套循环,我怎么能快速完成呢?

编辑: 例如:

featureMatrix = np.empty((len(featureDict.values()[0]),
       len(featureDict.values()[0][0,:]),
       len(featureDict.keys())))

for k,keys in enumerate(featureDict.keys()):
   value=featureDict[keys]
   for i in range(0,len(value[:,0]),1):
       for j in range(0,len(value[0,:]),1):
           featureMatrix[i,j,k]=value[i,j]

1 个答案:

答案 0 :(得分:4)

dict - 离合器是无序的,所以你可能不想简单地堆叠它们,但你可以简单地用array3d = np.dstack(somedict.values())堆叠值。

以下是一些示例案例:

>>> somedict = dict(a = np.arange(4).reshape(2,2),
                    b = np.arange(4).reshape(2,2) + 10,
                    c = np.arange(4).reshape(2,2) + 100,
                    d = np.arange(4).reshape(2,2) + 1000)

>>> array3d = np.dstack(somedict.values())
>>> array3d.shape
(2, 2, 4)
>>> array3d # unordered because of dict unorderedness, order depends for all practical purposes on chance
array([[[  10,    0, 1000,  100],
        [  11,    1, 1001,  101]],

       [[  12,    2, 1002,  102],
        [  13,    3, 1003,  103]]])

或者如果你想堆叠它按字典的键排序:

>>> array3d = np.dstack((somedict[i] for i in sorted(somedict.keys())))
>>> array3d    # sorted by the keys!
array([[[   0,   10,  100, 1000],
        [   1,   11,  101, 1001]],

       [[   2,   12,  102, 1002],
        [   3,   13,  103, 1003]]])