我試圖從平面文件中導入文本並將其轉換爲單行內的浮點值。我看過this post,它有相同的錯誤,但我沒有找到哪些字符在我的輸入文件中無效。或者我有語法錯誤?將導入的字符串轉換爲浮點數與numpy的loadtext
導入爲字符串的打印結果:
data = np.loadtxt(file, delimiter='\t', dtype=str)
print(data[0:2])
...
[["b'Time'" "b'Percent'"]
["b'99'" "b'0.067'"]]
嘗試導入爲float:
# Import data as floats and skip the first row: data_float
data_float = np.loadtxt(data, delimiter='\t', dtype=float, skiprows=1)
它引發以下錯誤:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
data_float = np.loadtxt(data, delimiter='\t', dtype=float, skiprows=1)
File "<stdin>", line 848, in loadtxt
items = [conv(val) for (conv, val) in zip(converters, vals)]
File "<stdin>", line 848, in <listcomp>
items = [conv(val) for (conv, val) in zip(converters, vals)]
ValueError: could not convert string to float: b'["b\'99\'" "b\'0.067\'"]'
順便說一句,我也看到了,它解釋了b
角色,但我不認爲這是他問。
由第一個答案提出附加的故障排除步驟:
data = np.loadtxt(file, delimiter="\tb'", dtype=str)
返回:
array(["b'Time\\tPercent'", "b'99\\t0.067'", "b'99\\t0.133'",
"b'99\\t0.067'", "b'99\\t0'", "b'99\\t0'", "b'0\\t0.5'",
"b'0\\t0.467'", "b'0\\t0.857'", "b'0\\t0.5'", "b'0\\t0.357'",
"b'0\\t0.533'", "b'5\\t0.467'", "b'5\\t0.467'", "b'5\\t0.125'",
"b'5\\t0.4'", "b'5\\t0.214'", "b'5\\t0.4'", "b'10\\t0.067'",
"b'10\\t0.067'", "b'10\\t0.333'", "b'10\\t0.333'", "b'10\\t0.133'",
"b'10\\t0.133'", "b'15\\t0.267'", "b'15\\t0.286'", "b'15\\t0.333'",
"b'15\\t0.214'", "b'15\\t0'", "b'15\\t0'", "b'20\\t0.267'",
"b'20\\t0.2'", "b'20\\t0.267'", "b'20\\t0.437'", "b'20\\t0.077'",
"b'20\\t0.067'", "b'25\\t0.133'", "b'25\\t0.267'", "b'25\\t0.412'",
"b'25\\t0'", "b'25\\t0.067'", "b'25\\t0.133'", "b'30\\t0'",
"b'30\\t0.071'", "b'30\\t0'", "b'30\\t0.067'", "b'30\\t0.067'",
"b'30\\t0.133'"],
dtype='<U16')
這是我的意見,我很樂意刪除它,但你能解釋爲什麼第一個? – Bobby
我現在解決了它,看到我發佈的答案,我也可以刪除整個問題,因爲答案是微不足道的,但也許它會幫助別人。 – Bobby
刪除問題:它的偏離主題。 m SO ------密切彈出。這個問題是由於無法再現的問題或簡單的印刷錯誤造成的。雖然類似的問題可能在這裏討論,但這個問題的解決方式不太可能有助於未來的讀者。這通常可以通過識別並密切檢查在發佈之前重現問題所需的最短程序來避免。 – Merlin