Home > database >  Repeat every element in a 2D array to a 2D output
Repeat every element in a 2D array to a 2D output

Time:04-26

I have a 2D array like this one -

import numpy as np

arr = np.array([(1,2),(4,6)])

I want this output -

arr2 = array([1,1,2,2], [4,4,6,6])

What I have so far is giving me 1D output:

arr2=[]
for i in range(len(arr)):
    a = arr[i,:]
    for j in range(len(a)):
        arr2.append(a[j])
        arr2.append(a[j])

np.array(arr2)
array([1, 1, 2, 2, 4, 4, 6, 6])

any suggestions would be highly appreciated. Thank you.

CodePudding user response:

You can use np.repeat:

arr = np.repeat(arr, 2).reshape((2, -1))
print(arr)

Prints:

[[1 1 2 2]
 [4 4 6 6]]
  • Related