CyprUS CyprUS - 1 month ago 10
Python Question

How to replace each array element by 4 copies in Python?

How do I use numpy / python array routines to do this ?

E.g. If I have array

[ [1,2,3,4,]]
, the output should be

[[1,1,2,2,],
[1,1,2,2,],
[3,3,4,4,],
[3,3,4,4]]


Thus, the output is array of double the row and column dimensions. And each element from original array is repeated three times.

What I have so far is this

def operation(mat,step=2):
result = np.array(mat,copy=True)
result[::2,::2] = mat
return result


This gives me array

[[ 98.+0.j 0.+0.j 40.+0.j 0.+0.j]
[ 0.+0.j 0.+0.j 0.+0.j 0.+0.j]
[ 29.+0.j 0.+0.j 54.+0.j 0.+0.j]
[ 0.+0.j 0.+0.j 0.+0.j 0.+0.j]]


for the input

[[98 40]
[29 54]]


The array will always be of even dimensions.

Answer

Use np.repeat():

In [9]: A = np.array([[1, 2, 3, 4]])
In [10]: np.repeat(np.repeat(A, 2).reshape(2, 4), 2, 0)
Out[10]: 
array([[1, 1, 2, 2],
       [1, 1, 2, 2],
       [3, 3, 4, 4],
       [3, 3, 4, 4]])

Explanation:

First off you can repeat the arrya items:

  In [30]: np.repeat(A, 3)
  Out[30]: array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4])

then all you need is reshaping the result (based on your expected result this can be different):

  In [32]: np.repeat(A, 3).reshape(2, 3*2)
  array([[1, 1, 1, 2, 2, 2],
         [3, 3, 3, 4, 4, 4]])

And now you should repeat the result along the the first axis:

  In [34]: np.repeat(np.repeat(A, 3).reshape(2, 3*2), 3, 0)
  Out[34]: 
  array([[1, 1, 1, 2, 2, 2],
         [1, 1, 1, 2, 2, 2],
         [1, 1, 1, 2, 2, 2],
         [3, 3, 3, 4, 4, 4],
         [3, 3, 3, 4, 4, 4],
         [3, 3, 3, 4, 4, 4]])