np.full(size,0)与np.zeros(size)与np.empty() [英] np.full(size, 0) vs. np.zeros(size) vs. np.empty()

查看:562
本文介绍了np.full(size,0)与np.zeros(size)与np.empty()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您要选择以下三种用零初始化数组的方式中的一种,那么您会选择哪一种?为什么?

If you were to choose one of the following three ways of initializing an array with zeros which one would you choose and why?

my_arr_1 = np.full(size, 0) 

my_arr_2 = np.zeros(size)

my_arr_3 = np.empty(size)
my_arr_3[:] = 0

推荐答案

由于其名称,我会使用np.zeros.我永远不会使用第三个成语,因为

I'd use np.zeros, because of its name. I would never use the third idiom because

  1. 它需要两个语句而不是一个表达式,并且

  1. it takes two statements instead of a single expression and

对于NumPy员工来说,最难优化.实际上,在NumPy中 1.10,尽管对索引进行了所有优化,但np.zeros仍然是最快的选择:

it's harder for the NumPy folks to optimize. In fact, in NumPy 1.10, np.zeros is still the fastest option, despite all the optimizations to indexing:

>>> %timeit np.zeros(1e6)
1000 loops, best of 3: 804 µs per loop
>>> %timeit np.full(1e6, 0)
1000 loops, best of 3: 816 µs per loop
>>> %timeit a = np.empty(1e6); a[:] = 0
1000 loops, best of 3: 919 µs per loop

更大的数组,可与@John Zwinck的结果进行比较:

Bigger array for comparison with @John Zwinck's results:

>>> %timeit np.zeros(1e8)
100000 loops, best of 3: 9.66 µs per loop
>>> %timeit np.full(1e8, 0)
1 loops, best of 3: 614 ms per loop
>>> %timeit a = np.empty(1e8); a[:] = 0
1 loops, best of 3: 229 ms per loop

这篇关于np.full(size,0)与np.zeros(size)与np.empty()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆