python - 重新格式化文本文件,以便在 python 中使用 numpy 数组?
问题描述
我有一小段代码用于从数据集中查找置信区间。
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)
感谢大家花时间提供帮助,非常感谢,特别是对于像我这样的新编码员。
解决方案
您可以将其读取为字符串,然后将空格替换,
为使其类似于列表并用于eval
将字符串列表转换为list
类型,最后转换为 numpy 数组。
对于您给定的虚拟输入
li = """[-10.197663 -22.970129 -15.678419 -15.306197
-12.09961 -11.845362 -18.10553 -25.370747
-19.34831 -22.45586]"""
np.array(eval(li.replace(' ',',')))
array([-10.197663, -22.970129, -15.678419, -27.405807, -11.845362,
-18.10553 , -44.719057, -22.45586 ])
对于给定的输入文件 -这里的解决方案是
import re
li = open('test1.txt', 'r').read()
np.array(eval(re.sub(r'(\n +| +)',',',li)))
array([-10.197663 , -22.970129 , -15.678419 , -15.306197 ,
-0.38851437, -12.09961 , -11.845362 , -18.10553 ,
-25.370747 , -20.575884 , -19.34831 , -22.45586 ,
-31.209 , -19.68507 , -31.07194 , -28.4792 ,
...])
推荐阅读
- c++ - 调用 'std::set 没有匹配的函数
::插入(std::size_t&) - minikube - 尝试在 minikube 上使用 jenkins-x 部署应用程序时出错
- python - PyQt:如何连接自动添加的按钮
- android - 是否有任何功能可以帮助在颤振应用中添加朋友并对其进行排序?
- google-chrome - 如何在 Chrome 中更新 Sass 的更改
- angular-material - MatSidenavModule 不是参考
- typescript - 这种语法在 React Native 和 TypeScript 中意味着什么?
- firebase - 云功能的更新、创建等功能是否受 Firestore 安全规则的影响?
- angular - Angular Interceptor 不发送响应头
- swift - 限制子视图中的按钮触摸