python - 在 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
解决方案
看起来你想要一个扩展的标准差,为此我会使用 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)
推荐阅读
- r - R中值“43857.33”的日期格式是什么?
- javascript - 如何根据屏幕宽度添加/删除或切换类?
- python - 无法将变量传递给 Paraview 脚本
- c# - ASP.NET CORE 的等效 MVC 代码是什么?
- angular - 将 FormGroup 中的控件配置为不返回值
- javascript - 仅取消设置但不破坏 php 会话是否安全?
- javascript - JavaScript:mergeSort 返回 RangeError:超出最大调用堆栈大小
- python - 如何调用Python程序
- mysql - 调节由子查询选择的列
- python - Docker.py 如何使用 stdin_open=True 停止容器?