2017-05-09 192 views
0

我在.txt文件中讀取以下字符串Python 2.7將2d字符串數組轉換爲浮點數組

{{1,2,3,0},{4,5,6,7},{8, -1,9,0}}

使用lin = lin.strip()以除去 '\ N'

然後我代替{和}至[和]使用

lin = lin.replace ("{", "[") 

lin = lin.replace ("}", "]") 

我的目標是林轉換成浮動2d數組。所以,我沒有

my_matrix = np.array(lin, dtype=float) 

,但我得到一個錯誤信息:「ValueError異常:無法將字符串轉換爲float:[1,2,3,0],[1,1,1,2],[0 ,-1,3,9]]「

刪除dtype,我得到一個字符串數組。我已經嘗試將lin乘以1.0,使用.astype(float)創建lin的副本,但似乎沒有任何工作。

+0

你期望什麼樣的浮球?你想獲得一系列花車嗎? '[[1.0,2.0,3.0,0.0],[4.0,5.0,6.0,7.0],[8.0,-1.0,9.0,0.0]]或某種串聯'1230.4567'? – Hans

+0

可能你最好的選擇是使用JSON庫: 'import json; json.loads(filecontent)' 這應該給你一個整數數組,你可以用 – Hans

+0

@ kamik423做計算我想要一個浮點數組[[1.0,2.0,3.0,0.0],[4.0,5.0, 6.0,7.0],[8.0,-1.0,9.0,0.0]] – Pat

回答

0

我使用JSON庫來解析文件的內容,然後遍歷數組並將每個元素轉換爲float。然而,一個整數解決方案可能已經足夠你想要的。那個更快更短。

import json 

fc = '{{1,2,3,0},{4,5,6,7},{8,-1,9,0}}' 

a = json.loads(fc.replace('{','[').replace('}',']')) 

print(a) # a is now array of integers. this might be enough 

for linenumber, linecontent in enumerate(a): 
    for elementnumber, element in enumerate(linecontent): 
     a[linenumber][elementnumber] = float(element) 

print(a) # a is now array of floats 

較短的解決方案

import json 

fc = '{{1,2,3,0},{4,5,6,7},{8,-1,9,0}}' 

a = json.loads(fc.replace('{','[').replace('}',']')) 

print(a) # a is now array of integers. this might be enough 

a = [[float(c) for c in b] for b in a] 

print(a) # a is now array of floats 

(同時適用於Python 2和3)

+0

這節省了我的一天! – Pat

0
import numpy as np 

readStr = "{{1,2,3,0},{4,5,6,7},{8,-1,9,0}}" 
readStr = readStr[2:-2] 
# Originally read string is now -> "1,2,3,0},{4,5,6,7},{8,-1,9,0" 

line = readStr.split("},{") 
# line is now a list object -> ["1,2,3,0", "4,5,6,7", "8,-1,9,0"] 

array = [] 
temp = [] 
# Now we iterate through 'line', convert each element into a list, and 
#  then append said list to 'array' on each iteration of 'line' 
for string in line: 
    num_array = string.split(',') 
    for num in num_array: 
     temp.append(num) 
    array.append(temp) 
    temp = [] 

# Now with 'array' -> [[1,2,3,0], [4,5,6,7], [8,-1,9,0]] 
my_matrix = np.array(array, dtype = float) 

# my_matrix = [[1.0, 2.0, 3.0, 0.0] 
#    [4.0, 5.0, 6.0, 7.0] 
#    [8.0, -1.0, 9.0, 0.0]] 

雖然這可能不是最完美的解決方案,我認爲這是容易跟蹤和給你準確的你在找什麼。

相關問題