Reputation: 422
I have a dictionary where the values are 3 column matrices. 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. Running python 3.6.
Upvotes: 0
Views: 1281
Reputation: 231665
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)
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
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. But other wise the same.
Upvotes: 1