[英]Merging 2 numpy arrays into a dictionary
I have 2 numpy darrays and want to create a dictionary from them.我有 2 个 numpy darray,想用它们创建一个字典。 For example {(7.9,3.8,6.4,2): 2}
例如 {(7.9,3.8,6.4,2): 2}
import numpy as np
little_X_test= np.array([[7.9, 3.8, 6.4, 2],
[5.2, 4.1, 1.5, 0.1],
[6.9, 3.1, 5.1, 2.3]])
little_y_test= np.array([2, 0, 2])
d = {}
for A, B in zip(little_X_test, little_y_test):
d[A] = B
Error message错误信息
TypeError: unhashable type: 'numpy.ndarray'
类型错误:不可散列类型:'numpy.ndarray'
Numpy arrays, lists, and other mutable object are non hashable. Numpy 数组、列表和其他可变对象是不可散列的。
If you convert to tuple this works as the object is immutable.如果您转换为元组,这将起作用,因为对象是不可变的。
NB.注意。 You don't have to use a loop, use the
dict
constructor directly不用循环,直接使用
dict
构造函数
import numpy as np
little_X_test= np.array([[7.9, 3.8, 6.4, 2],
[5.2, 4.1, 1.5, 0.1],
[6.9, 3.1, 5.1, 2.3]])
little_y_test= np.array([2, 0, 2])
d = dict(zip(map(tuple, little_X_test), little_y_test))
output:输出:
>>> d
{(7.9, 3.8, 6.4, 2.0): 2,
(5.2, 4.1, 1.5, 0.1): 0,
(6.9, 3.1, 5.1, 2.3): 2}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.