python - 为什么 numpy.array() 有时很慢?

标签 python numpy scipy

我正在使用 numpy.array() 函数从列表创建 numpy.float64 ndarrays。

我注意到,当列表不包含 None 或提供列表列表时,这会非常慢。

下面是一些带时间的例子。有明显的解决方法,但为什么这么慢?

无列表示例:

### Very slow to call array() with list of None
In [3]: %timeit numpy.array([None]*100000, dtype=numpy.float64)
1 loops, best of 3: 240 ms per loop

### Problem doesn't exist with array of zeroes
In [4]: %timeit numpy.array([0.0]*100000, dtype=numpy.float64)
100 loops, best of 3: 9.94 ms per loop

### Also fast if we use dtype=object and convert to float64
In [5]: %timeit numpy.array([None]*100000, dtype=numpy.object).astype(numpy.float64)
100 loops, best of 3: 4.92 ms per loop

### Also fast if we use fromiter() insead of array()
In [6]: %timeit numpy.fromiter([None]*100000, dtype=numpy.float64)
100 loops, best of 3: 3.29 ms per loop

列表列表示例:

### Very slow to create column matrix
In [7]: %timeit numpy.array([[0.0]]*100000, dtype=numpy.float64)
1 loops, best of 3: 353 ms per loop

### No problem to create column vector and reshape
In [8]: %timeit numpy.array([0.0]*100000, dtype=numpy.float64).reshape((-1,1))
100 loops, best of 3: 10 ms per loop

### Can use itertools to flatten input lists
In [9]: %timeit numpy.fromiter(itertools.chain.from_iterable([[0.0]]*100000),dtype=numpy.float64).reshape((-1,1))
100 loops, best of 3: 9.65 ms per loop

最佳答案

我已将此报告为一个 numpy 问题。报告和补丁文件在这里:

https://github.com/numpy/numpy/issues/3392

修补后:

# was 240 ms, best alternate version was 3.29
In [5]: %timeit numpy.array([None]*100000)
100 loops, best of 3: 7.49 ms per loop

# was 353 ms, best alternate version was 9.65
In [6]: %timeit numpy.array([[0.0]]*100000)
10 loops, best of 3: 23.7 ms per loop

关于python - 为什么 numpy.array() 有时很慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16819261/

相关文章:

python - 获取 numpy 中出现次数最少的值的索引

python - 无法在 Python 中加载以前转储的 pickle 文件

python - 使用 Pandas 处理 GPS 数据

python - 准确找到最小的特征值

python - 使用numpy构建两个数组的所有组合的数组

python - 将文件从 jupyter 笔记本上传到 github 时出错

python - 在稀疏矩阵上执行外积求和

scipy - 如何直接获得scipy插值的梯度?

python - 避免对特定列 pandas 进行舍入

python - pyparsing 开始和结束字符串相同