2016-12-12 65 views
0

我需要將包含逗號分隔值的文本文件讀入2D numpy陣列。每行的前2個值包含numpy數組的索引值,第三個值包含要存儲在數組中的值。作爲一個問題,索引值是基於1的,需要轉換爲numpy使用的基於0的索引值。我已經使用genfromtxt和loadtxt回顧了文檔和示例,但是我仍不清楚如何去做。我也嘗試下面的代碼,但沒有成功:使用文本文件中的索引值將文本文件中的值讀入2D numpy陣列

a = np.arange(6).reshape(2,3) 

for line in infile: 
    fields = line.split() #split fields inti list 
    rindex = int(fields[0]) - 1 
    cindex = int(fields[1]) - 1 
    a[rindex,cindex] = float(fields[2]) 

這裏是輸入文件的例子:

1,1,10.1 
1,2,11.2 
1,3,12.3 
2,3,13.4 
2,2,14.5 
2,3,15.6 

這裏是我想要的輸出數組。理想情況下,我希望它可以處理任何數組大小,而不必預先定義數組的大小。

10.1 11.2 12.3 
13.4 14.5 15.6 
+0

'數據= NP .genfromtxt('path_to_file',converters = {0:lambda x:int(x) - 1,1:lambda x:int(x) - 1},delimiter =「,」)。reshape(2,3)'。 – Abdou

回答

0

這裏有一種方法可以做到這一點。使用numpy.genfromtxt()將數據讀入具有三個字段的結構化數組。的行和列索引被拉出結構化陣列的並用於計算出所需的陣列的形狀,以及涉及使用numpy的的「花式」索引值分配給新的數組:

In [46]: !cat test_data.csv 
1,1,10.1 
1,2,11.2 
1,3,12.3 
2,3,13.4 
2,2,14.5 
2,3,15.6 

In [47]: data = np.genfromtxt('test_data.csv', dtype=None, delimiter=',', names=['i', 'j', 'value']) 

In [48]: data 
Out[48]: 
array([(1, 1, 10.1), (1, 2, 11.2), (1, 3, 12.3), (2, 3, 13.4), 
     (2, 2, 14.5), (2, 3, 15.6)], 
     dtype=[('i', '<i8'), ('j', '<i8'), ('value', '<f8')]) 

In [49]: rows = data['i'] 

In [50]: cols = data['j'] 

In [51]: nrows = rows.max() 

In [52]: ncols = cols.max() 

In [53]: a = np.zeros((nrows, ncols)) 

In [54]: a[rows-1, cols-1] = data['value'] 

In [55]: a 
Out[55]: 
array([[ 10.1, 11.2, 12.3], 
     [ 0. , 14.5, 15.6]])