我有一小块代码,用于从数据集中查找置信区间。
from scipy import stats
import numpy as np
a = np.loadtxt("test1.txt")
mean, sigma = np.mean(a), np.std(a)
conf_int = stats.norm.interval(0.95, loc=mean,
scale=sigma)
print(conf_int)
但是,我的文本文件 (test1.txt) 是一个数字列表,其中 a) 在开头和结尾处有方括号 b) 不在相等的列中。
“[-10.197663 -22.970129 -15.678419 -15.306197
-12.09961 -11.845362 -18.10553 -25.370747
-19.34831 -22.45586]
np.loadtxt 似乎确实不喜欢这样,所以有什么方法可以使用函数按原样读取和使用数据或重新格式化数据?
任何帮助将不胜感激!
更新,所以我设法用下面的代码删除我的括号
with open('test1.txt', 'r') as my_file:
text = my_file.read()
text = text.replace("[", "")
text = text.replace("]", "")
with open('clean.txt', 'w') as my_file:
my_file.write(text)
a = np.loadtxt("clean.txt")
mean, sigma = np.mean(a), np.std(a)
conf_int = stats.norm.interval(0.95, loc=mean,
scale=sigma)
print(conf_int)
只需重新格式化 clean.txt,使其位于一列中,以便 np.array 能够识别它。
最终更新
使用 @David Hoffman 建议的代码和我从上面进行的长期工作,我设法让它工作;见下文
from scipy import stats
import numpy as np
with open('test1.txt', 'r') as my_file:
text = my_file.read()
text = text.replace("[", "")
text = text.replace("]", "")
with open('clean.txt', 'w') as my_file:
my_file.write(text)
a = np.array(list(map(float, text.strip("[]").split())))
mean, sigma = np.mean(a), np.std(a)
conf_int = stats.norm.interval(0.95, loc=mean,
scale=sigma)
print(conf_int)
感谢大家花时间提供帮助,非常感谢,特别是对于像我这样的新程序员。
最佳答案
这就是我要做的:
import numpy as np
from scipy import stats
import requests
link = "https://pastebin.pl/view/raw/929f5228"
response = requests.get(link)
text = response.text
# with open("test1.txt", "r") as my_file:
# text = my_file.read()
a = np.array(list(map(float, text.strip("[]").split())))
mean, sigma = np.mean(a), np.std(a)
conf_int = stats.norm.interval(0.95, loc=mean, scale=sigma)
print(conf_int)
注释行适用于您有文件的情况。
字符串处理行中包含了很多内容:
- 文本字符串被清理(删除括号)
- 干净的文本由空格分隔(任何长度的连续空格字符都被视为分隔符)
- 每个拆分 token 都会转换为
float
(这是map
部分) map
生成器转换为列表并传递给numpy
数组函数
正如 @Dishin 所说,您的输入文件的格式有些奇怪。如果您可以控制文件的写入方式(例如通过 LabVIEW 程序或其他 Python 脚本),则可能值得以更广泛接受的格式(如 .csv
)格式化数据,以便实现诸如 np.loadtxt
(或 Excel 等程序)可以更轻松地读取它。
如果您坚持使用文件原样,您可以创建一个小实用函数,例如:
def loader(filename):
with open(filename, "r") as my_file:
text = my_file.read()
return np.array(list(map(float, text.strip("[]").split())))
在您的脚本中重用。
关于python - 重新格式化文本文件,以便它可以在 python 中使用 numpy 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63304742/