[英]Numpy array using values of an object
I have an object -> {0: 0.8, 1: 0.2, 2: 0, 3: 0}我有一个对象 -> {0: 0.8, 1: 0.2, 2: 0, 3: 0}
I want to convert it to a numpy array, where the keys are the index, and the values are the values of the array -> [0.8, 0.2, 0, 0]我想把它转换成一个 numpy 数组,其中键是索引,值是数组的值 -> [0.8, 0.2, 0, 0]
Whats the fastest and efficient way of doing this?这样做的最快和有效的方法是什么?
I am using a for loop, but is there a better way of doing this?我正在使用 for 循环,但有没有更好的方法来做到这一点?
假设您的字典名为dict
:
numpy_array = np.array([*dict.values()])
keys
, items
and values
are the fastest way to get 'things' from a dict. keys
、 items
和values
是从字典中获取“东西”的最快方法。 Otherwise you have to iterate on the keys.否则,您必须对键进行迭代。 A general approach that allows for skipped indices, and out-of-order ones:允许跳过索引和无序索引的通用方法:
In [81]: adict = {0: 0.8, 1: 0.2, 2: 0, 3: 0}
In [82]: keys = list(adict.keys())
In [83]: arr = np.zeros(max(keys)+1) # or set your own size
In [84]: arr[keys] = list(adict.values())
In [85]: arr
Out[85]: array([0.8, 0.2, 0. , 0. ])
The above answer gives dict_values, but was in the right direction上面的答案给出了 dict_values,但方向是正确的
the correct way to do it is:正确的做法是:
d = {0: 0.8, 1: 0.2, 2: 0, 3: 0}
np_array = np.array(list(d.values()))
Dictionary is inherently orderless.字典本质上是无序的。 You would need to sort your values according to your keys (assuming you do not have a missing key in your dictionary):您需要根据您的键对您的值进行排序(假设您的字典中没有丢失的键):
a = {0: 0.8, 1: 0.2, 2: 0, 3: 0}
np.array([i[1] for i in sorted(a.items(), key=lambda x:x[0])])
Another way of doing it is sorting in numpy:另一种方法是在 numpy 中排序:
b = np.array(list(a.items()))
b[b[:,0].argsort()][:,1]
output:输出:
[0.8, 0.2, 0, 0]
A solution if input dict is not ordered or has missing values:如果输入 dict 未排序或缺少值的解决方案:
d = {1:1.1, 2:2.2, 0: 0.8, 4:4.4}
sz = 1+max(d.keys()) # or len(d) if you are sure there are no missing values
x = np.full(sz, np.nan)
x[list(d.keys())] = list(d.values())
x
#array([0.8, 1.1, 2.2, nan, 4.4])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.