亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

計算文本文件的標準偏差

計算文本文件的標準偏差

慕妹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 關注
  • 234 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號