无论输入值是什么,np.genfromtxt
将始终返回False
。
使用dtype='u1'
我得到了预期的“1”。但是使用 dtype='b1'
(Numpy 的 bool)我得到“False”。
最佳答案
我不知道这是否是一个错误,但到目前为止,只有当文件包含文字字符串“False”和“True”:
In [21]: bool_lines = ['False,False', 'False,True', 'True,False', 'True,True']
In [22]: genfromtxt(bool_lines, delimiter=',', dtype=bool)
Out[22]:
array([[False, False],
[False, True],
[ True, False],
[ True, True]], dtype=bool)
如果你的数据是0和1,你可以将其读取为整数,然后转换为bool:
In [26]: bits = ['0,0', '0,1', '1,0', '1,1']
In [27]: genfromtxt(bits, delimiter=',', dtype=np.uint8).astype(bool)
Out[27]:
array([[False, False],
[False, True],
[ True, False],
[ True, True]], dtype=bool)
或者您可以为每列使用转换器
In [28]: cnv = lambda s: bool(int(s))
In [29]: converters = {0: cnv, 1: cnv}
In [30]: genfromtxt(bits, delimiter=',', dtype=bool, converters=converters)
Out[30]:
array([[False, False],
[False, True],
[ True, False],
[ True, True]], dtype=bool)
关于numpy.genfromtxt 无法正确读取 bool 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27223428/