gpt4 book ai didi

python - 重新格式化文本文件以便它可以在 python 中使用 numpy 数组?

转载 作者:行者123 更新时间:2023-12-04 09:13:59 25 4
gpt4 key购买 nike

我有一小段代码用于从数据集中查找置信区间。

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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com