首页 > 解决方案 > 在 Python 中计算大列表标准差的更有效方法

问题描述

您好我正在尝试计算大约 20,000 个值长的列表的一堆标准偏差。这是我的代码示例:

from statistics import stdev

def main():
    a = [x for x in range(0,20000)]
    b = []

    for x in range(2, len(a) + 2):
        b.append(stdev(a[:x]))

    print(b)

main()

这种方法非常慢,我正在尝试找出一种方法来提高效率。任何帮助表示赞赏。谢谢你。

[Done] exited with code=null in 820.376 seconds

标签: pythonpython-3.x

解决方案


看起来你想要一个扩展的标准差,为此我会使用 pandas 库和pandas.Series.expanding方法:

In [156]: main()[:5]
Out[156]: 
[0.7071067811865476,
 1.0,
 1.2909944487358056,
 1.5811388300841898,
 1.8708286933869707]

In [157]: pd.Series(range(20000)).expanding().std()[:5]
Out[157]: 
0         NaN
1    0.707107
2    1.000000
3    1.290994
4    1.581139
dtype: float64

如果需要,您可以轻松地切掉第一个元素并转换为列表:

In [158]: pd.Series(range(20000)).expanding().std()[1:6].tolist()
Out[158]: 
[0.7071067811865476,
 1.0,
 1.2909944487358056,
 1.5811388300841898,
 1.8708286933869707]

尽管 Series 对于处理时间序列来说是一种比列表更有用的数据类型,而且性能肯定更高:

In [159]: %timeit pd.Series(range(20000)).expanding().std()
1.07 ms ± 30.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

推荐阅读