很高兴您提供了文件示例:
In [1]: txt="""135,10,125,10,1
...: 230,16,214,19,not 1
...: 226,16,210,19,1
...: 231,16,215,19,not 1
...: 205,16,189,17,not 1"""
loadtxt 接受字符串列表代替文件:
In [2]: np.loadtxt(txt.splitlines(),delimiter=',')
...
ValueError: could not convert string to float: 'not 1'
它试图返回一个浮点数组,但not 1 字符串会出现问题:
genfromtxt 类似,但在可以创建浮动时给出nan:
In [3]: np.genfromtxt(txt.splitlines(),delimiter=',')
Out[3]:
array([[135., 10., 125., 10., 1.],
[230., 16., 214., 19., nan],
[226., 16., 210., 19., 1.],
[231., 16., 215., 19., nan],
[205., 16., 189., 17., nan]])
您可以跳过问题栏:
In [4]: np.loadtxt(txt.splitlines(),delimiter=',', usecols=[0,1,2,3])
Out[4]:
array([[135., 10., 125., 10.],
[230., 16., 214., 19.],
[226., 16., 210., 19.],
[231., 16., 215., 19.],
[205., 16., 189., 17.]])
或者因为无论如何你要将数组拆分为两个数组:
In [8]: np.genfromtxt(txt.splitlines(),delimiter=',', usecols=[0,1,2,3], dtype=int)
Out[8]:
array([[135, 10, 125, 10],
[230, 16, 214, 19],
[226, 16, 210, 19],
[231, 16, 215, 19],
[205, 16, 189, 17]])
In [9]: np.genfromtxt(txt.splitlines(),delimiter=',', usecols=[4], dtype=None, encoding=None)
Out[9]: array(['1', 'not 1', '1', 'not 1', 'not 1'], dtype='<U5')
dtype=None 让它为每一列选择合适的数据类型。
In [10]: np.genfromtxt(txt.splitlines(),delimiter=',', dtype=None, encoding=N
...: one)
Out[10]:
array([(135, 10, 125, 10, '1'), (230, 16, 214, 19, 'not 1'),
(226, 16, 210, 19, '1'), (231, 16, 215, 19, 'not 1'),
(205, 16, 189, 17, 'not 1')],
dtype=[('f0', '<i8'), ('f1', '<i8'), ('f2', '<i8'), ('f3', '<i8'), ('f4', '<U5')])
这是一个结构化数组,每列都有一个field。并且具有更高级的 dtype 规范:
In [13]: np.genfromtxt(txt.splitlines(),delimiter=',', dtype='4i,U5', encoding=None)
Out[13]:
array([([135, 10, 125, 10], '1'), ([230, 16, 214, 19], 'not 1'),
([226, 16, 210, 19], '1'), ([231, 16, 215, 19], 'not 1'),
([205, 16, 189, 17], 'not 1')],
dtype=[('f0', '<i4', (4,)), ('f1', '<U5')])
In [14]: _['f0']
Out[14]:
array([[135, 10, 125, 10],
[230, 16, 214, 19],
[226, 16, 210, 19],
[231, 16, 215, 19],
[205, 16, 189, 17]], dtype=int32)
In [15]: __['f1']
Out[15]: array(['1', 'not 1', '1', 'not 1', 'not 1'], dtype='<U5')
到目前为止,我还没有尝试解析或转换那些“非 1”字符串。我们可以构造一个converter,把它变成一个数字,比如0。
如果我定义一个转换器函数,比如:
def foo(astr):
if astr==b'not 1':
astr = b'0'
return int(astr)
In [31]: np.genfromtxt(txt.splitlines(),delimiter=',', converters={4:foo}, dtype=int)
Out[31]:
array([[135, 10, 125, 10, 1],
[230, 16, 214, 19, 0],
[226, 16, 210, 19, 1],
[231, 16, 215, 19, 0],
[205, 16, 189, 17, 0]])
或者如果转换器返回一个浮点数:
def foo(astr):
if astr==b'not 1':
astr = b'0'
return float(astr)
In [39]: np.genfromtxt(txt.splitlines(),delimiter=',', converters={4:foo})
Out[39]:
array([[135., 10., 125., 10., 1.],
[230., 16., 214., 19., 0.],
[226., 16., 210., 19., 1.],
[231., 16., 215., 19., 0.],
[205., 16., 189., 17., 0.]])