为了账号安全,请及时绑定邮箱和手机立即绑定

计算文本文件的标准偏差

计算文本文件的标准偏差

慕妹3146593 2021-10-10 19:00:52
我正在尝试计算“ClosePrices”列中所有数据的标准偏差,请参阅 pastebin https://pastebin.com/JtGr672m我们需要计算所有 1029 个浮点数的一个标准差。这是我的代码:ins1 = open("bijlage.txt", "r")for line in ins1:        numbers = [(n) for n in number_strings]         i = i + 1        ClosePriceSD = []        ClosePrice = float(data[0][5].replace(',', '.'))        ClosePriceSD.append(ClosePrice)def sd_calc(data):    n = 1029    if n <= 1:        return 0.0    mean, sd = avg_calc(data), 0.0    # calculate stan. dev.    for el in data:        sd += (float(el) - mean)**2    sd = math.sqrt(sd / float(n-1))    return sddef avg_calc(ls):    n, mean = len(ls), 0.0    if n <= 1:        return ls[0]    # calculate average    for el in ls:        mean = mean + float(el)    mean = mean / float(n)    return meanprint("Standard Deviation:")print(sd_calc(ClosePriceSD))print()所以我要计算的是“收盘价”部分下所有浮动的标准偏差。好吧,我有这个“ClosePrice = float(data[0][5].replace(',', '.'))”这应该计算ClosePrice下所有浮点数的标准偏差,但它只从数据中计算出来[0][5]。但我希望它计算 ClosePrice 下所有 1029 个浮点数的一个标准差
查看完整描述

2 回答

?
智慧大石

TA贡献1946条经验 获得超3个赞

我认为您的错误在开头的 for 循环中。你有,for line in ins1但你永远不会line在循环内使用。在您的循环中,您还使用了之前未定义的number_string和data。


以下是从 txt 文件中提取数据的方法。


with open("bijlage.txt", "r") as ff:

    ll = ff.readlines() #extract a list, each element is a line of the file


data = []

for line in ll[1:]: #excluding the first line wich is an header

    d = line.split(';')[5] #split each line in a list using semicolon as a separator and keep the element with index 5

    data.append(float(d.replace(',', '.'))) #substituting the comma with the dot in the string and convert it to a float


print data #data is a list with all the numbers you want

您应该能够从这里计算均值和标准差。


查看完整回答
反对 回复 2021-10-10
  • 2 回答
  • 0 关注
  • 190 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号