2016-02-23 204 views
-4

我想知道我們是否可以逐行閱讀數組。例如:Python:如何在numpy數組中逐行閱讀?

array([[ 0.28, 0.22, 0.23, 0.27], 
     [ 0.12, 0.29, 0.34, 0.21], 
     [ 0.44, 0.56, 0.51, 0.65]]) 

要讀取的第一線以陣列形式來執行一些操作,然後與第二行陣列繼續:

array([0.28,0.22,0.23,0.27]) 

什麼產生上述陣列是因爲這兩條線代碼:

from numpy import genfromtxt 
single=genfromtxt('single.csv',delimiter=',') 

single.csv

0.28, 0.22, 0.23, 0.27 
0.12, 0.29, 0.34, 0.21 
0.44, 0.56, 0.51, 0.65 

使用readlines()看起來像生成列表而不是數組。就我而言,我使用的是csv文件。我試圖逐行使用這些值的行,而不是將它們全部一起使用以避免內存錯誤。誰能幫我?

with open('single.csv') as single: 
    single=single.readlines() 
+0

'array'是一種類型嗎? –

+0

你的'csv'中有'array([0.28,0.22,0.23,0.27])'嗎?這不是'csv'格式。 –

+0

'readlines'產生一個字符串列表。解析每一行以獲取數字 – hpaulj

回答

5

可以使用np.fromstring

import numpy as np 
with open('single.csv') as f: 
    lines=f.readlines() 
    for line in lines: 
     myarray = np.fromstring(line, dtype=float, sep=',') 
     print(myarray) 

看到http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.fromstring.htmlHow to read csv into record array in numpy?

+0

對不起,我不熟悉np.fromstring。並且它返回了這個錯誤:NameError:name'double'沒有被定義 – Xiong89

+0

@熊89看到我的編輯 – maazza

0
for list in array: 
    print(list) 
    for item in list: 
     print(item) 

給出了輸出:

[0.28, 0.22, 0.23, 0.27] 
0.28 
0.22 
0.23 
0.27 
[0.12, 0.29, 0.34, 0.21] 
0.12 
0.29 
0.34 
0.21 
[0.44, 0.56, 0.51, 0.65] 
0.44 
0.56 
0.51 
0.65 
1

似乎你沒有經驗閱讀Python中的文件。讓我通過一個實例在一些細節工作,在IPython中iteractive會議

創建一個多行文本,以模擬文件

In [23]: txt="""0.28, 0.22, 0.23, 0.27 
0.12, 0.29, 0.34, 0.21 
0.44, 0.56, 0.51, 0.65""" 

把它分解成線,模擬的結果readlines

In [24]: txt=txt.splitlines(True) 

In [25]: txt 
Out[25]: 
['0.28, 0.22, 0.23, 0.27\n', 
'0.12, 0.29, 0.34, 0.21\n', 
'0.44, 0.56, 0.51, 0.65'] 

我可以將它轉換爲一個數組genfromtxt(您可以像這樣將結果傳遞到readlinesgenfromtxt

In [26]: np.genfromtxt(txt, delimiter=',') 
Out[26]: 
array([[ 0.28, 0.22, 0.23, 0.27], 
     [ 0.12, 0.29, 0.34, 0.21], 
     [ 0.44, 0.56, 0.51, 0.65]]) 

我可以遍歷行,剝離上\n和拆分「」

In [27]: for line in txt: 
    print line.strip().split(',') 
    ....:  
['0.28', ' 0.22', ' 0.23', ' 0.27'] 
['0.12', ' 0.29', ' 0.34', ' 0.21'] 
['0.44', ' 0.56', ' 0.51', ' 0.65'] 

我可以將每個字符串轉換成浮子與列表理解:

In [28]: for line in txt:         
    print [float(x) for x in line.strip().split(',')] 
    ....:  
[0.28, 0.22, 0.23, 0.27] 
[0.12, 0.29, 0.34, 0.21] 
[0.44, 0.56, 0.51, 0.65] 

或者通過將迭代放在另一個列表理解中,我可以得到一列數字列表:

In [29]: data=[[float(x) for x in line.strip().split(',')] for line in txt] 

In [30]: data 
Out[30]: [[0.28, 0.22, 0.23, 0.27], [0.12, 0.29, 0.34, 0.21], [0.44, 0.56, 0.51, 0.65]] 

我可以把它轉換成一個數組

In [31]: np.array(data) 
Out[31]: 
array([[ 0.28, 0.22, 0.23, 0.27], 
     [ 0.12, 0.29, 0.34, 0.21], 
     [ 0.44, 0.56, 0.51, 0.65]]) 

genfromtxt基本上通過順序去 - 讀取線,劈裂它們,將字符串轉換爲值,最後創建從列表中的陣列。

有捷徑,但我認爲你會從完成這些步驟的細節中受益。這與基本的Python字符串和列表操作一樣,都是關於數組的。

+0

謝謝:)非常有幫助。 – Xiong89