计算文本文件的标准偏差

我正在尝试计算“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 sd


def 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 mean

print("Standard Deviation:")

print(sd_calc(ClosePriceSD))

print()

所以我要计算的是“收盘价”部分下所有浮动的标准偏差。


好吧,我有这个“ClosePrice = float(data[0][5].replace(',', '.'))”这应该计算ClosePrice下所有浮点数的标准偏差,但它只从数据中计算出来[0][5]。但我希望它计算 ClosePrice 下所有 1029 个浮点数的一个标准差


慕妹3146593
浏览 191回答 2
2回答

智慧大石

我认为您的错误在开头的 for 循环中。你有,for line in ins1但你永远不会line在循环内使用。在您的循环中,您还使用了之前未定义的number_string和data。以下是从 txt 文件中提取数据的方法。with open("bijlage.txt", "r") as ff:&nbsp; &nbsp; ll = ff.readlines() #extract a list, each element is a line of the filedata = []for line in ll[1:]: #excluding the first line wich is an header&nbsp; &nbsp; d = line.split(';')[5] #split each line in a list using semicolon as a separator and keep the element with index 5&nbsp; &nbsp; data.append(float(d.replace(',', '.'))) #substituting the comma with the dot in the string and convert it to a floatprint data #data is a list with all the numbers you want您应该能够从这里计算均值和标准差。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python