genfromtxt 用于csv 文件,这些文件具有一致的行和列,一个简单的表。像 () 这样的额外字符可能会搞砸。分隔符也不一致(默认为空白)
带样本
In [68]: txt = """(( 1 2 3) xxx)
...: (-1 2 3) yyy)
...: """
In [69]: np.genfromtxt(txt.splitlines(), usecols=(1,2,3))
Out[69]:
array([[ 1., 2., nan],
[ 2., nan, nan]])
nan 用于无法制成浮点数的字符串。
没有usecols,我们看到它在每行中获得不同数量的列。
In [70]: np.genfromtxt(txt.splitlines())
Traceback (most recent call last):
File "<ipython-input-70-3a7e73045f73>", line 1, in <module>
np.genfromtxt(txt.splitlines())
File "/usr/local/lib/python3.8/dist-packages/numpy/lib/npyio.py", line 2124, in genfromtxt
raise ValueError(errmsg)
ValueError: Some errors were detected !
Line #2 (got 4 columns instead of 5)
这是它对每一行所做的事情:
In [71]: for row in txt.splitlines():print(row.split())
['((', '1', '2', '3)', 'xxx)']
['(-1', '2', '3)', 'yyy)']
您需要在将文件传递给genfromtxt 之前清理文件,或者使用您自己的解析来处理您想要的 ()。
使用干净的文件:
In [72]: txt = """1 2 3 xxx
...: -1 2 3 yyy
...: """
In [73]: np.genfromtxt(txt.splitlines(),usecols=(0,1,2))
Out[73]:
array([[ 1., 2., 3.],
[-1., 2., 3.]])