This is arguably the way of creating an array filled with certain values, because it explicitly describes what is being achieved (and it can in principle be very efficient since it performs a very specific task).
回答 1
已为Numpy 1.7.0更新:(@ Rolf Bartstra的提示)。
a=np.empty(n); a.fill(5) 最快。
以降序排列:
%timeit a=np.empty(1e4); a.fill(5)100000 loops, best of 3:5.85 us per loop
%timeit a=np.empty(1e4); a[:]=5100000 loops, best of 3:7.15 us per loop
%timeit a=np.ones(1e4)*510000 loops, best of 3:22.9 us per loop
%timeit a=np.repeat(5,(1e4))10000 loops, best of 3:81.7 us per loop
%timeit a=np.tile(5,[1e4])10000 loops, best of 3:82.9 us per loop
Updated for Numpy 1.7.0:(Hat-tip to @Rolf Bartstra.)
a=np.empty(n); a.fill(5) is fastest.
In descending speed order:
%timeit a=np.empty(1e4); a.fill(5)
100000 loops, best of 3: 5.85 us per loop
%timeit a=np.empty(1e4); a[:]=5
100000 loops, best of 3: 7.15 us per loop
%timeit a=np.ones(1e4)*5
10000 loops, best of 3: 22.9 us per loop
%timeit a=np.repeat(5,(1e4))
10000 loops, best of 3: 81.7 us per loop
%timeit a=np.tile(5,[1e4])
10000 loops, best of 3: 82.9 us per loop
You should also always avoid iterating like you are doing in your example. A simple a[:] = v will accomplish what your iteration does using numpy broadcasting.
回答 3
显然,不仅绝对速度而且速度顺序(如user1579844所报告)均取决于机器。这是我发现的:
a=np.empty(1e4); a.fill(5) 最快
以降序排列:
timeit a=np.empty(1e4); a.fill(5)# 100000 loops, best of 3: 10.2 us per loop
timeit a=np.empty(1e4); a[:]=5# 100000 loops, best of 3: 16.9 us per loop
timeit a=np.ones(1e4)*5# 100000 loops, best of 3: 32.2 us per loop
timeit a=np.tile(5,[1e4])# 10000 loops, best of 3: 90.9 us per loop
timeit a=np.repeat(5,(1e4))# 10000 loops, best of 3: 98.3 us per loop
timeit a=np.array([5]*int(1e4))# 1000 loops, best of 3: 1.69 ms per loop (slowest BY FAR!)
Apparently, not only the absolute speeds but also the speed order (as reported by user1579844) are machine dependent; here’s what I found:
a=np.empty(1e4); a.fill(5) is fastest;
In descending speed order:
timeit a=np.empty(1e4); a.fill(5)
# 100000 loops, best of 3: 10.2 us per loop
timeit a=np.empty(1e4); a[:]=5
# 100000 loops, best of 3: 16.9 us per loop
timeit a=np.ones(1e4)*5
# 100000 loops, best of 3: 32.2 us per loop
timeit a=np.tile(5,[1e4])
# 10000 loops, best of 3: 90.9 us per loop
timeit a=np.repeat(5,(1e4))
# 10000 loops, best of 3: 98.3 us per loop
timeit a=np.array([5]*int(1e4))
# 1000 loops, best of 3: 1.69 ms per loop (slowest BY FAR!)
So, try and find out, and use what’s fastest on your platform.
v = 7
rows = 3
cols = 5
a = numpy.tile(v, (rows,cols))
a
Out[1]:
array([[7, 7, 7, 7, 7],
[7, 7, 7, 7, 7],
[7, 7, 7, 7, 7]])
Although tile is meant to ’tile’ an array (instead of a scalar, as in this case), it will do the job, creating pre-filled arrays of any size and dimension.