2016-07-26 119 views
1

我正在學習numpy中genfromtxt的I/O函數。 我試過numpy的用戶指南中的一個例子。它是關於genfromtxt的註釋參數。numpy中genfromtxt的註釋參數

下面是從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.]] 

下面我嘗試:

結果出來:

genfromtxt:空輸入文件:「<在0x0000020555DC5EB8 _io.BytesIO對象>」 warnings.warn( 'genfromtxt:空輸入文件: 「%S」' %FNAME)

我知道問題是與數據。任何人都可以教我如何設置示例中顯示的數據? 非常感謝。

+0

爲第一個genfromtxt參數嘗試使用StringIO而不是BytesIO – Jonas

+2

爲什麼要在數據中插入反斜槓? – BrenBarn

回答

0

請嘗試以下。首先,不要使用"\"。其次,你爲什麼用.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.]]) 
+0

謝謝。刪除所有「\」後,我能夠得到結果。 我使用python3.5,所以我需要使用.BytesIO()。 –

+0

我不使用py3,所以我沒有這個問題..祝你好運。 – Merlin

0

ipython3(PY 3)交互會話我可以這樣做:

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)也適用,但它是額外的工作。

當然,另一種選擇是將這些行復制到文本編輯器並將它們保存爲簡單的文本文件。將副本粘貼到交互式會話中是一個方便的捷徑,但不是必需的。

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'] 
+0

。@ hpaulj does StringIO在py3中的行爲與py2不同,不是py3的用戶。 – Merlin

+0

謝謝你的多行字符串輸入法。我有三重引號的問題,「\」 –

+0

'genfromtxt'預計它的輸入是字節字符串(沒有Unicode)。Py3使用unicode字符串作爲默認格式,'StringIO'處理默認值(不管版本)。這是2和3之間的第二個最常見的區別(最常見的是'print(...)'表達式)。 – hpaulj