Python TypeError:创建numpy数组时无法理解数据类型
有一个布尔条件列表,我想生成一个矩阵,其中的列表有假值或真值 例如Python TypeError:创建numpy数组时无法理解数据类型,python,arrays,numpy,Python,Arrays,Numpy,有一个布尔条件列表,我想生成一个矩阵,其中的列表有假值或真值 例如 值=[[True,False],[False],[True],[True,False]] 结果将是 False True 0 1 1 1 1 0 2 0 1 3 1 1 我试着这样做,如下所示: nodes = [True, False] values = [[True, False], [False], [True], [True, False]] r
值=[[True,False],[False],[True],[True,False]]
结果将是
False True
0 1 1
1 1 0
2 0 1
3 1 1
我试着这样做,如下所示:
nodes = [True, False]
values = [[True, False], [False], [True], [True, False]]
res = np.array([[int(cond in vals) for vals in values] for cond in nodes],
dtype=[(node, int) for node in nodes])
但是我得到了错误
TypeError:data-type-not-readed
尝试dtype=int
,然后我们得到
import numpy as np
nodes = [True, False]
values = [[True, False], [False], [True], [True, False]]
res = np.array([[cond in vals for vals in values] for cond in nodes], dtype=int)
print(res)
# Output
[[1 0 1 1]
[1 1 0 1]]
dtype
应该代表什么?我认为它只需要是int
就可以指定数组中的每个值都是int
@tadhgsen,它表示res
值类型。让np.array分析数据:in[348]:数组([[True,False],[False],[True],[True,False])->Out[348]:数组([[True,False],[False],[True],[True],[True,False]],dtype=object)您是否尝试过dtype=int
?我想这就是你所需要的一切了…@Tadhgmdonald Jensen是的,它与dtype=int
thx一起工作当dtype
被指定时,你甚至不需要显式地强制转换为相同的类型,所以int(VAL中的cond)
有点多余,它在VAL中可能只是cond