Is it possible to strip a numpy array in 2 dimensions with a single call

I have a 2d numpy array

a = array([[1,2],[3,4]])

I want to

array([[1,1,2,2],
       [1,1,2,2],
       [3,3,4,4],
       [3,3,4,4]])

I can do it with 2 calls numpy.repeat

repeat(repeat(a,2,axis=0),2,axis=1)

But is there any combination of parameters for this with a single call?

+4
source share
1 answer

You can create such an array using numpy.lib.stride_tricks.as_strided():

s = min(a.strides)
as_strided(a, shape=(2,2,2,2), strides=(2*s,0,s,0)).reshape(4,4)
#array([[1, 1, 2, 2],
#       [1, 1, 2, 2],
#       [3, 3, 4, 4],
#       [3, 3, 4, 4]])

reshape() copies data, creating a continuous array at the end.

NOTE : Although it is possible to do this at a time, your original solution is 4X faster on my computer.

+1
source

Source: https://habr.com/ru/post/1544289/


All Articles