2011-10-05 67 views
9

我想重复沿着轴线0和1轴的阵列的元件,用于分别M和N次:如何沿两个轴重复一个数组的元素?

import numpy as np 

a = np.arange(12).reshape(3, 4) 
b = a.repeat(2, 0).repeat(2, 1) 
print(b) 

[[ 0 0 1 1 2 2 3 3] 
[ 0 0 1 1 2 2 3 3] 
[ 4 4 5 5 6 6 7 7] 
[ 4 4 5 5 6 6 7 7] 
[ 8 8 9 9 10 10 11 11] 
[ 8 8 9 9 10 10 11 11]] 

此工作原理,但我想知道是否有更好的方法,而没有创建临时数组。

+1

另请参阅[本文](http://stackoverflow.com/q/32846846/2566083)上使用kron,repeat和stride_tricks以及速度分析给出的答案。 – mlh3789

回答

6

您可以使用直积,看到numpy.kron

>>> a = np.arange(12).reshape(3,4) 
>>> print np.kron(a, np.ones((2,2), dtype=a.dtype)) 
[[ 0 0 1 1 2 2 3 3] 
[ 0 0 1 1 2 2 3 3] 
[ 4 4 5 5 6 6 7 7] 
[ 4 4 5 5 6 6 7 7] 
[ 8 8 9 9 10 10 11 11] 
[ 8 8 9 9 10 10 11 11]] 

你原来的方法也没关系,但!

2

另一种解决方案是使用as_stridedkron比使用repeat要慢两倍。我发现as_strided在很多情况下比双重repeat快很多(小阵[< 250x250],每个维as_strided只有两倍的速度变慢)。所述as_strided特技如下:

a = arange(1000000).reshape((1000, 1000)) # dummy data 

from numpy.lib.stride_tricks import as_strided 
N, M = 4,3 # number of time to replicate each point in each dimension 
H, W = a.shape 
b = as_strided(a, (H, N, W, M), (a.strides[0], 0, a.strides[1], 0)).reshape((H*N, W*M)) 

此工作原理是利用长度为0的进步导致numpy的读取相同的值多次(直到它到达下一个维度)。最后的reshape确实复制了数据,但只有一次不像使用将复制数据两次的双重repeat

+1

[这里是链接](https://stackoverflow.com/a/32848377/3923281)到提出'as_strided'的解决方案,以及时间安排;-) –

相关问题