【发布时间】:2021-12-06 11:25:08
【问题描述】:
我正在尝试学习如何使用 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(有点像您使用列表的方式)
- 向 np.arrays 添加数据的最佳方式是什么
- 如果我想使用 for 循环遍历数组(有点像使用列表的方式),最好的方法是什么?
所有帮助都非常受欢迎和高度赞赏
【问题讨论】:
-
不要将数组视为列表。这会给你带来很多问题。
-
您是否花时间阅读
numpy for absolute beginners文档? -
np.appenddocs 两次说它返回一个 copy,这与就地工作的列表追加不同。正确的做法是构建列表,并从中创建一个数组。 -
@hpaulj:请为您提供反馈。我现在已经根据您提供的改进和建议更新了我的代码。
标签: python arrays numpy for-loop