How can I calculate the variance of a list in python?(如何计算python中列表的方差?)
问题描述
如果我有这样的列表:
results=[-14.82381293, -0.29423447, -13.56067979, -1.6288903, -0.31632439,
0.53459687, -1.34069996, -1.61042692, -4.03220519, -0.24332097]
我想在 Python 中计算此列表的方差,即均值的平方差的平均值.
I want to calculate the variance of this list in Python which is the average of the squared differences from the mean.
我该怎么办?访问列表中的元素来进行计算让我无法获得平方差.
How can I go about this? Accessing the elements in the list to do the computations is confusing me for getting the square differences.
推荐答案
您可以使用 numpy 的内置函数 var
:
You can use numpy's built-in function var
:
import numpy as np
results = [-14.82381293, -0.29423447, -13.56067979, -1.6288903, -0.31632439,
0.53459687, -1.34069996, -1.61042692, -4.03220519, -0.24332097]
print(np.var(results))
这给你 28.822364260579157
如果 - 无论出于何种原因 - 您不能使用 numpy
和/或您不想为其使用内置函数,您也可以使用例如手动"计算它列表理解:
If - for whatever reason - you cannot use numpy
and/or you don't want to use a built-in function for it, you can also calculate it "by hand" using e.g. a list comprehension:
# calculate mean
m = sum(results) / len(results)
# calculate variance using a list comprehension
var_res = sum((xi - m) ** 2 for xi in results) / len(results)
这会给你相同的结果.
如果您对标准差感兴趣,可以使用numpy.std:
If you are interested in the standard deviation, you can use numpy.std:
print(np.std(results))
5.36864640860051
@Serge Ballesta 很好地解释了方差 n
和 n 之间的区别-1
.在 numpy 中,您可以使用选项 ddof
轻松设置此参数;它的默认值是 0
,所以对于 n-1
的情况你可以简单地做:
@Serge Ballesta explained very well the difference between variance n
and n-1
. In numpy you can easily set this parameter using the option ddof
; its default is 0
, so for the n-1
case you can simply do:
np.var(results, ddof=1)
@Serge Ballesta 的回答中给出了手工"解决方案.
The "by hand" solution is given in @Serge Ballesta's answer.
两种方法都产生 32.024849178421285
.
你也可以为std
设置参数:
np.std(results, ddof=1)
5.659050201086865
这篇关于如何计算python中列表的方差?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何计算python中列表的方差?


- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01