我正在学习numpy中genfromtxt的I/O功能。我试过了numpy用户指南中的一个例子。这是关于the的注释论点。
这里是numpy:用户指南中的示例
>>> data = """#
... # Skip me !
... # Skip me too !
... 1, 2
... 3, 4
... 5, 6 #This is the third line of the data
... 7, 8
... # And here comes the last line
... 9, 0
... """
>>> np.genfromtxt(StringIO(data), comments="#", delimiter=",")
[[ 1. 2.]
[ 3. 4.]
[ 5. 6.]
[ 7. 8.]
[ 9. 0.]]I尝试如下:
data = """# \
# Skip me ! \
# Skip me too ! \
1, 2 \
3, 4 \
5, 6 #This is the third line of the data \
7, 8 \
# And here comes the last line \
9, 0 \
"""
a = np.genfromtxt(io.BytesIO(data.encode()), comments = "#", delimiter = ",")
print (a)结果出来:
genfromtxt:空输入文件:"<_io.BytesIO object at 0x0000020555DC5EB8>“warnings.warn('genfromtxt:空输入文件:"%s"‘% fname)
我知道问题在于数据。任何人都可以教我如何设置数据,如本例所示?非常感谢。
发布于 2016-07-26 04:41:22
试试下面。首先,不要使用"\"。第二,为什么要使用.BytesIO()使用StringIO()?
import numpy as np
from StringIO import StringIO
data = """#
# Skip me !
# Skip me too !
1, 2
3, 4
5, 6 #This is the third line of the data
7, 8
# And here comes the last line
9, 0
"""
np.genfromtxt(StringIO(data), comments="#", delimiter=",")
array([[ 1., 2.],
[ 3., 4.],
[ 5., 6.],
[ 7., 8.],
[ 9., 0.]])发布于 2016-07-26 04:51:31
在ipython3 (py3)交互式会话中,我可以这样做:
In [326]: data = b"""#
...: ... # Skip me !
...: ... # Skip me too !
...: ... 1, 2
...: ... 3, 4
...: ... 5, 6 #This is the third line of the data
...: ... 7, 8
...: ... # And here comes the last line
...: ... 9, 0
...: ... """
In [327]:
In [327]: data
Out[327]: b'#\n# Skip me !\n# Skip me too !\n1, 2\n3, 4\n5, 6 #This is the third line of the data\n7, 8\n# And here comes the last line\n9, 0\n'
In [328]: np.genfromtxt(data.splitlines(),comments='#', delimiter=',')
Out[328]:
array([[ 1., 2.],
[ 3., 4.],
[ 5., 6.],
[ 7., 8.],
[ 9., 0.]])在Python3中,字符串需要是字节;在Py2中,这是默认的。
对于多行字符串输入(三元引号),不要使用\。这是行的延续。你想保留\n
data = b"""
one
two
"""注意,我还可以使用:
data = '#\n# Skip me\n...'使用显式\n。
genfromtxt使用给它行的任何可迭代性。所以我给了它一个线的列表-用分裂线产生的。StringIO (或Py3中的ByteIO )也能工作,但它需要额外的工作。
当然,另一种选择是将这些行复制到文本编辑器中,并将它们保存为一个简单的文本文件。复制-n-粘贴到交互会话是一个方便的捷径,但没有必要。
In [329]: data.splitlines()
Out[329]:
[b'#',
b'# Skip me !',
b'# Skip me too !',
b'1, 2',
b'3, 4',
b'5, 6 #This is the third line of the data',
b'7, 8',
b'# And here comes the last line',
b'9, 0']https://stackoverflow.com/questions/38580927
复制相似问题