我正在嘗試學習如何使用 np.arrays,作為一項練習任務,我正在開發一個從檔案中讀取資料并將其添加到一些陣列的程式。
該函式read_from_file()應該回傳一些包含排序資料點的陣列,以便可以使用 matplot lib 輕松繪制它們。
到目前為止我寫的代碼是
import numpy as np
import matplotlib.pyplot as plt
def read_from_file(filename):
a = np.array
b = np.array
c = np.array
d = np.array
with open(filename, "r") as infile:
infile.readline()
for line in infile:
infile.readline()
delta_x = float(line[9:21].strip())
approx = float(line[34:50].strip())
abs_error = float(line[91:103].strip())
relative_error = float(line[121:133].strip())
n_ = int(line[137:].strip())
a = np.append(delta_x)
b = np.append(approx)
c = np.append(abs_error)
d = np.array(relative_error)
return a, b, c, d
test = read_from_file("datafile.txt")
我試圖讀取的資料檔案看起來像這樣(我只關心其他每一行)
0.1 0.045590188541076104
delta_x: 1.000000e-01, df_approx: 4.5590188541e-01, df_exact: 5.0000000000e-01, abs_error: 4.409811e-02, rel_error: 8.819623e-02, n=1
0.01 0.00495661575773676
delta_x: 1.000000e-02, df_approx: 4.9566157577e-01, df_exact: 5.0000000000e-01, abs_error: 4.338424e-03, rel_error: 8.676848e-03, n=2
...................................
delta_x: 1.000000e-18, df_approx: 0.0000000000e 00, df_exact: 5.0000000000e-01, abs_error: 5.000000e-01, rel_error: 1.000000e 00, n=18
1e-19 0.0
delta_x: 1.000000e-19, df_approx: 0.0000000000e 00, df_exact: 5.0000000000e-01, abs_error: 5.000000e-01, rel_error: 1.000000e 00, n=19
我的問題是 我認為我正在設法按預期提取資料(在串列等上對其進行測驗)。但是當我嘗試將它添加到 np.arrays 時,它給了我這個錯誤訊息:
Traceback (most recent call last):
File "C:/(...).py", line 55, in <module>
test = read_from_file("datafile.txt")
File "C:/(...).py", line 48, in read_from_file
a = np.append(delta_x)
File "<__array_function__ internals>", line 4, in append
TypeError: _append_dispatcher() missing 1 required positional argument: 'values'
我的問題是:
- 有沒有人足夠好心為我提供解決這個問題的方法?
- 我如何向 np.arrays 添加資料(有點像你如何處理串列)
- What is the best way of adding data to np.arrays
- If I want to use a for-loop to iterate through an array (kind of like how you would do it with lists), what is the best way to do it?
All help is much welcomed and highly appreciated
uj5u.com熱心網友回復:
- 要創建一個空的 numpy 陣列(當您不知道最終形狀時),您應該使用
np.array([]) np.append接受兩個引數:要附加到的陣列和要附加的值。你只通過一個。enumerate在檔案上,因此您只能決議您實際需要的行。
嘗試:
def read_from_file(filename):
a = np.array([])
b = np.array([])
c = np.array([])
d = np.array([])
with open(filename) as infile:
for i, line in enumerate(infile):
if i%2 == 0:
continue
contents = line.split(", ")
values = [c.split(":")[-1].strip() for c in contents]
a = np.append(a, float(values[0]))
b = np.append(b, float(values[1]))
c = np.append(c, float(values[2]))
d = np.append(d, float(values[3]))
return a,b,c,d
a, b, c, d = read_from_file("file.txt")
>>> a
array([1.e-01, 1.e-02, 1.e-18, 1.e-19])
>>> b
array([0.45590189, 0.49566158, 0. , 0. ])
>>> c
array([0.5, 0.5, 0.5, 0.5])
>>> d
array([0.04409811, 0.00433842, 0.5 , 0.5 ])
uj5u.com熱心網友回復:
學習使用時numpy,您需要numpy手頭有檔案,并花時間閱讀基礎知識以及您使用的每個功能的幫助。不要天真地將陣列“像串列一樣”對待。
def read_from_file(filename):
a = np.array
np.array是一個函式。你為什么把它分配給一個變數?陣列是用類似的運算式創建的a=np.array([[1,2],[3,4]])。重讀np.array檔案。
with open(filename, "r") as infile:
infile.readline()
for line in infile:
infile.readline()
delta_x = float(line[9:21].strip())
...
a = np.append(delta_x)
np.append 檔案說它從兩個輸入中復制,
In [239]: x =np.append(np.array([1,2,3]), 4)
In [240]: x
Out[240]: array([1, 2, 3, 4])
它不像串列追加那樣就地操作。該np.append檔案盡量做到這一點。唯一更清楚的是完全洗掉該函式!
In [241]: x=[1,2,3]
In [242]: x.append(4)
In [243]: x
Out[243]: [1, 2, 3, 4]
如果您必須迭代地構建一個陣列,請堅持使用串列直到最后
a = [] for _ in loop: a.append(values) arr = np.array(a)
如果正確使用,numpy 陣列可以比串列更快,如檔案所述。如果像串列一樣使用它們,它們不會更快。如果有的話,它們會更慢,而且通常甚至不起作用。
我懷疑您的檔案可以np.genfromtxt使用delimiter指定列寬的版本讀取。
delimiter : str, int, or sequence, optional
The string used to separate values. By default, any consecutive
whitespaces act as delimiter. An integer or sequence of integers
can also be provided as width(s) of each field.
說到genfromtxt,該函式逐行讀取檔案,將結果收集在串列串列中(每行一個子串列)。然后它從最后的結果生成二維陣列。它不會嘗試像串列一樣以增量方式構建陣列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/324807.html
