Sha*_*han 4 python numpy scipy
我想在python中创建一些具有相同值初始化的特定类型的指定维度的数组.我可以使用特定大小的numpy数组,但我不知道如何使用特定值初始化它们.当然我不想使用零()或一些()
非常感谢.
有很多方法可以做到这一点.我遇到的第一个单线是tile:
>>> numpy.tile(2, 25)
array([2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2])
Run Code Online (Sandbox Code Playgroud)
您可以平铺任何形状的值:
>>> numpy.tile(2, (5, 5))
array([[2, 2, 2, 2, 2],
[2, 2, 2, 2, 2],
[2, 2, 2, 2, 2],
[2, 2, 2, 2, 2],
[2, 2, 2, 2, 2]])
Run Code Online (Sandbox Code Playgroud)
但是,正如下面的一些答案所示,这不是最快的方法.它设计用于平铺任何大小的数组,而不仅仅是单个值,所以如果你真的只想用一个值填充数组,那么先分配数组然后使用切片赋值要快得多:
>>> a = numpy.empty((5, 5), dtype=int)
>>> a[:] = 2
>>> a
array([[2, 2, 2, 2, 2],
[2, 2, 2, 2, 2],
[2, 2, 2, 2, 2],
[2, 2, 2, 2, 2],
[2, 2, 2, 2, 2]])
Run Code Online (Sandbox Code Playgroud)
根据我做过的一些测试,没有更快的方法.但是,下面答案中提到的两种方法同样快:ndarray.fill和numpy.full.
这些测试都是在ipython运行OS 10.12.6的新Mac上使用Python 3.6.1完成的.定义:
def fill_tile(value, shape):
return numpy.tile(value, shape)
def fill_assign(value, shape, dtype):
new = numpy.empty(shape, dtype=dtype)
new[:] = value
return new
def fill_fill(value, shape, dtype):
new = numpy.empty(shape, dtype=dtype)
new.fill(value)
return new
def fill_full(value, shape, dtype):
return numpy.full(shape, value, dtype=dtype)
def fill_plus(value, shape, dtype):
new = numpy.zeros(shape, dtype=dtype)
new += value
return new
def fill_plus_oneline(value, shape, dtype):
return numpy.zeros(shape, dtype=dtype) + value
for f in [fill_assign, fill_fill, fill_full, fill_plus, fill_plus_oneline]:
assert (fill_tile(2, (500, 500)) == f(2, (500, 500), int)).all()
Run Code Online (Sandbox Code Playgroud)
tile 确实很慢:
In [3]: %timeit fill_tile(2, (500, 500))
947 µs ± 10.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Run Code Online (Sandbox Code Playgroud)
用切片的分配关系ndarray.fill和numpy.full第一名:
In [4]: %timeit fill_assign(2, (500, 500), int)
102 µs ± 1.37 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [5]: %timeit fill_fill(2, (500, 500), int)
102 µs ± 1.99 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [6]: %timeit fill_full(2, (500, 500), int)
102 µs ± 1.47 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
Run Code Online (Sandbox Code Playgroud)
就地广播添加只是稍微慢一些:
In [7]: %timeit fill_plus(2, (500, 500), int)
179 µs ± 3.7 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
Run Code Online (Sandbox Code Playgroud)
而非就地广播的加法只比这稍慢:
In [8]: %timeit fill_plus_oneline(2, (500, 500), int)
213 µs ± 4.74 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Run Code Online (Sandbox Code Playgroud)
怎么样:
shape = (100,100)
val = 3.14
dt = np.float
a = np.empty(shape,dtype=dt)
a.fill(val)
Run Code Online (Sandbox Code Playgroud)
这样你就可以设置并传递参数.另外,在时间方面
In [35]: %timeit a=np.empty(shape,dtype=dt); a.fill(val)
100000 loops, best of 3: 13 us per loop
In [36]: %timeit a=np.tile(val,shape)
10000 loops, best of 3: 102 us per loop
Run Code Online (Sandbox Code Playgroud)
所以使用emptywith fill似乎要快得多tile.