How to replace each element of an array with 4 instances in Python?

How can I use numpy / python array procedures for this?

eg. If I have an 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 an array of two sizes of rows and columns. And each element from the original array is repeated three times.

What I still have is

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

It gives me an 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 input

 [[98 40] [29 54]] 

The array will always have even sizes.

+5
source share
3 answers

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 you can repeat the arrya elements:

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

then you need to change the form of the result (depending on your expected result, this may 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 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]]) 
+3
source

Another approach might be np.kron -

 np.kron(a.reshape(-1,2),np.ones((2,2),dtype=int)) 

Basically, we convert the input array to a 2D array, preserving the second axis length=2 . Then np.kron essentially replicates the elements along both rows and columns for length 2 each with this array: np.ones((2,2),dtype=int) .

Run Example -

 In [45]: a Out[45]: array([7, 5, 4, 2, 8, 6]) In [46]: np.kron(a.reshape(-1,2),np.ones((2,2),dtype=int)) Out[46]: array([[7, 7, 5, 5], [7, 7, 5, 5], [4, 4, 2, 2], [4, 4, 2, 2], [8, 8, 6, 6], [8, 8, 6, 6]]) 

If you want to have lines 4 , use a.reshape(2,-1) instead.

+1
source

The best solution is to use numpy, but you can also use iteration:

 a = [[1, 2, 3, 4]] v = iter(a[0]) b = [] for i in v: n = next(v) [b.append([i for k in range(2)] + [n for k in range(2)]) for j in range(2)] print b >>> [[1, 1, 2, 2], [1, 1, 2, 2], [3, 3, 4, 4], [3, 3, 4, 4]] 
0
source

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


All Articles