简体   繁体   English

如何从具有矩阵值的字典中提取列数据?

[英]How to extract column data from a dictionary with matrix values?

I have a dictionary where the values are 3 column matrices. 我有一本字典,其中的值是3列矩阵。 I want to extract the third column of each value and concatenate them all together side by side into a single matrix. 我想提取每个值的第三列,并将它们并排连接在一起,形成一个矩阵。 I can't figure out how to do this as general slicing won't work on a dictionary. 我无法弄清楚该怎么做,因为普通切片在词典上不起作用。 Would dictionaries even be the best way to store this data or would Pandas be better? 词典甚至是存储此数据的最佳方法,还是熊猫会更好? I've tried doing list(my_dict.values()) but this doesn't seem to work anymore. 我已经尝试过执行list(my_dict.values()),但这似乎不再起作用。 Running python 3.6. 运行python 3.6。

字典图片

In [1]: dd = {'one':np.arange(12).reshape(4,3),'two':np.arange(12).reshape(4,3)*2}

If key order doesn't matter: 如果关键顺序无关紧要:

In [3]: dd.values()
Out[3]: 
dict_values([array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]]), array([[ 0,  2,  4],
       [ 6,  8, 10],
       [12, 14, 16],
       [18, 20, 22]])])

Not what we want (in PY3) 不是我们想要的(在PY3中)

In [4]: np.array(dd.values())
Out[4]: 
array(dict_values([array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]]), array([[ 0,  2,  4],
       [ 6,  8, 10],
       [12, 14, 16],
       [18, 20, 22]])]), dtype=object)

list(values()) looks good - giving a list of arrays which can be joined in different ways list(values())看起来不错-给出了可以以不同方式连接的数组列表

In [5]: np.array(list(dd.values()))
Out[5]: 
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8],
        [ 9, 10, 11]],

       [[ 0,  2,  4],
        [ 6,  8, 10],
        [12, 14, 16],
        [18, 20, 22]]])

In [7]: np.array(list(dd.values()))[:,:,2]
Out[7]: 
array([[ 2,  5,  8, 11],
       [ 4, 10, 16, 22]])

np.concatenate(list(dd.values()),axis=0) makes a 2d array instead of 3d, so the [:,2] would be 1d instead of 2d. np.concatenate(list(dd.values()),axis=0)创建2d数组而不是3d,因此[:,2]将是1d而不是2d。 But other wise the same. 但是其他方面也一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM