我想将 python 字典中的所有 numpy 数组(所有相同大小)连接到一个新数组。
dict = {'some_key_1':np.array([1,2,3,4]), 'some_key_2':np.array([2,3,4,5]), ...}
我希望看到的结果是:
result = np.array([[1,2,3,4],[2,3,4,5]])
最好的方法是什么?
编辑:python 2 和 3 的解决方案似乎略有不同。已接受的答案解决了 python 3 的问题。
请您参考如下方法:
在 Python 3 中,您需要先将 dict.values() 转换为列表。
The objects returned by dict.keys(), dict.values() and dict.items() are view objects. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes. (https://docs.python.org/3/library/stdtypes.html#typesmapping)
import numpy as np
data = {'some_key_1':np.array([1,2,3,4]), 'some_key_2':np.array([2,3,4,5])}
print(np.array(list(data.values())))
# [[1 2 3 4]
# [2 3 4 5]]
你得到一个二维数组,其中的行是随机排列的(Python dict 是无序的)。
要获得一维数组,您可以使用 np.concatenate :
print(np.concatenate(list(data.values())))
# [1 2 3 4 2 3 4 5]
如果顺序很重要,您可以使用元组列表或 OrderedDict而不是 dict。
