numpy.genfromtxt 无法正确读取 bool 数据

标签 numpy

无论输入值是什么,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/

相关文章:

python - 在 Pandas 中将一个时间序列插值到另一个时间序列

python - 如何分配属于不同人群的不确定性?

python - 遍历 n 维数组的通用函数

python - 在 Keras(tf 后端)中返回标量点积真的那么难吗?

python - 对numpy数组中的每个第n个条目进行二次采样

python - Numpy,给定范数返回可能的笛卡尔坐标

python - 高效的多精度数值数组

java - 如何在 Kotlin/Java 中对 Numpy 数组(Python)进行 base64 解码?

python - 在 Python 的 NumPy 中确定最高值的索引

python - 使用numpy在python中矢量化空间距离