I'd like to duplicate each line of an array N times. Is there a quick way to do so?
我想复制一个数组N次的每一行。有快速的方法吗?
Example (N=3):
示例(N = 3):
# INPUT
a=np.arange(9).reshape(3,3)
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
# OUTPUT
array([[0, 1, 2],
[0, 1, 2],
[0, 1, 2],
[3, 4, 5],
[3, 4, 5],
[3, 4, 5],
[6, 7, 8],
[6, 7, 8],
[6, 7, 8]])
2 个解决方案
#1
3
This is a job for np.repeat
:
这是nps的工作。
np.repeat(a,3,axis=0)
array([[0, 1, 2],
[0, 1, 2],
[0, 1, 2],
[3, 4, 5],
[3, 4, 5],
[3, 4, 5],
[6, 7, 8],
[6, 7, 8],
[6, 7, 8]])
Note that this is much faster then the other method.
注意,这比其他方法快得多。
N=100
%timeit np.repeat(a,N,axis=0)
100000 loops, best of 3: 4.6 us per loop
%timeit rows, cols = a.shape;b=np.hstack(N*(a,));b.reshape(N*rows, cols)
1000 loops, best of 3: 257 us per loop
N=100000
%timeit np.repeat(a,N,axis=0)
100 loops, best of 3: 3.93 ms per loop
%timeit rows, cols = a.shape;b=np.hstack(N*(a,));b.reshape(N*rows, cols)
1 loops, best of 3: 245 ms per loop
Also np.tile
is useful in similar situations.
np。tile在类似的情况下也很有用。
#2
1
>>> N = 3
>>> rows, cols = a.shape
>>> b=np.hstack(N*(a,))
>>> b
array([[0, 1, 2, 0, 1, 2, 0, 1, 2],
[3, 4, 5, 3, 4, 5, 3, 4, 5],
[6, 7, 8, 6, 7, 8, 6, 7, 8]])
>>> b.reshape(N*rows, cols)
array([[0, 1, 2],
[0, 1, 2],
[0, 1, 2],
[3, 4, 5],
[3, 4, 5],
[3, 4, 5],
[6, 7, 8],
[6, 7, 8],
[6, 7, 8]])
#1
3
This is a job for np.repeat
:
这是nps的工作。
np.repeat(a,3,axis=0)
array([[0, 1, 2],
[0, 1, 2],
[0, 1, 2],
[3, 4, 5],
[3, 4, 5],
[3, 4, 5],
[6, 7, 8],
[6, 7, 8],
[6, 7, 8]])
Note that this is much faster then the other method.
注意,这比其他方法快得多。
N=100
%timeit np.repeat(a,N,axis=0)
100000 loops, best of 3: 4.6 us per loop
%timeit rows, cols = a.shape;b=np.hstack(N*(a,));b.reshape(N*rows, cols)
1000 loops, best of 3: 257 us per loop
N=100000
%timeit np.repeat(a,N,axis=0)
100 loops, best of 3: 3.93 ms per loop
%timeit rows, cols = a.shape;b=np.hstack(N*(a,));b.reshape(N*rows, cols)
1 loops, best of 3: 245 ms per loop
Also np.tile
is useful in similar situations.
np。tile在类似的情况下也很有用。
#2
1
>>> N = 3
>>> rows, cols = a.shape
>>> b=np.hstack(N*(a,))
>>> b
array([[0, 1, 2, 0, 1, 2, 0, 1, 2],
[3, 4, 5, 3, 4, 5, 3, 4, 5],
[6, 7, 8, 6, 7, 8, 6, 7, 8]])
>>> b.reshape(N*rows, cols)
array([[0, 1, 2],
[0, 1, 2],
[0, 1, 2],
[3, 4, 5],
[3, 4, 5],
[3, 4, 5],
[6, 7, 8],
[6, 7, 8],
[6, 7, 8]])