简体   繁体   中英

Extend and forward fill numpy array

I'd like to duplicate each line of an array N times. Is there a quick way to do so?

Example (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]])

This is a job for np.repeat :

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.

>>> 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]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM