如何计算方差?

我的代码的目的是在列表列表中找到平均值和方差。约束是:如果在“linesort”中有两个或更多列表,其中前两个元素相等,则计算添加列表的第三个元素的平均值。我的问题是包括方差和平均值的计算,并返回一个包含 [a, b, mean,variance] 的列表。非常感谢你。


linesort = [[1, 2, 3.00], [1, 2, 5.00], [1, 4, 7.00], [1, 4, 3.00] ,[3, 6, 5.2]]

new = []

final = []

count=0

for el in linesort:

    new.append(el[:-1])


tnew = [tuple(t) for t in new]

setnew = set(tnew)

setnew = [list(t) for t in setnew]


for items in setnew:

    inds = [i for i,x in enumerate(new) if x == items]

    if len(inds) > 1:

        somma = 0

        for ind in inds:

            print(somma)

            somma = linesort[ind][2] + somma

        media = somma/len(inds)

        items.append(media)

        final.append(items)

print(final)

期望输出:


('Output: ', [[1, 2, 4.0,1.0], [1, 4, 5.0,4.0]])


至于差异,我想过这行代码,但我无法让它工作。


variance = float(sum((linesort[ind][2] - media) ** 2 for linesort[ind][2] in linesort) / len(linesort))


慕容708150
浏览 212回答 1
1回答

哆啦的时光机

您可以通过首先重新组织字典中的数据来简化代码,将前两个元素的元组作为键,并将相应的值放在列表中。您可以使用 adefaultdict使这更容易。然后,我们只需要计算每个列表的均值和方差。from collections import defaultdictlinesort = [[1, 2, 3.00], [1, 2, 5.00], [1, 4, 7.00], [1, 4, 3.00] ,[3, 6, 5.2]]# Let's first group the values: d = defaultdict(list)for x, y, val in linesort:    d[(x, y)].append(val)# d will be: {(1, 2): [3.0, 5.0], (1, 4): [7.0, 3.0], (3, 6): [5.2]}    # Now we can build the output list:out = []for (x, y), values in d.items():    n = len(values)    mean = sum(values)/n    variance = sum(x**2 for x in values)/n - mean**2    out.append([x, y, mean, variance])print(out)# [[1, 2, 4.0, 1.0], [1, 4, 5.0, 4.0], [3, 6, 5.2, 0.0]]要回答您的评论:如果您想省略只有一个值的情况,只需将最后一部分更改为:for (x, y), values in d.items():    n = len(values)    if n > 1:        mean = sum(values)/n        variance = sum(x**2 for x in values)/n - mean**2        out.append([x, y, mean, variance])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python