Home > database >  How to reshape an array using np tile
How to reshape an array using np tile

Time:03-28

I have a array X structured with shape 2, 5 as follows:

0, 6, 7, 9, 1
2, 4, 6, 2, 7

I'd like to reshape it to repeat each row n times as follows (example uses n = 3):

0, 6, 7, 9, 1
0, 6, 7, 9, 1
0, 6, 7, 9, 1
2, 4, 6, 2, 7
2, 4, 6, 2, 7
2, 4, 6, 2, 7

I have tried to use np.tile as follows, but it repeats as shown below:

np.tile(X, (3, 5))
0, 6, 7, 9, 1
2, 4, 6, 2, 7
0, 6, 7, 9, 1
2, 4, 6, 2, 7
0, 6, 7, 9, 1
2, 4, 6, 2, 7

How might i efficiently create the desired output?

CodePudding user response:

If a be the main array:

a = np.array([0, 6, 7, 9, 1, 2, 4, 6, 2, 7])

we can do this by first reshaping to the desired array shape and then use np.repeat as:

b = a.reshape(2, 5)
final = np.repeat(b, 3, axis=0)

It can be done with np.tile too, but it needs unnecessary extra operations, something as below. So, np.repeat will be the better choice.

test = np.tile(b, (3, 1))
final = np.concatenate((test[::2], test[1::2]))

CodePudding user response:

For complex repeats, I'd use np.kron instead:

np.kron(x, np.ones((2, 1), dtype=int))

For something relatively simple,

np.repeat(x, 2, axis=0)

CodePudding user response:

you can do this with numpy.tile like below:

a = np.array([
    [0, 6, 7, 9, 1],
    [2, 4, 6, 2, 7]
])
b = np.tile(a,3).reshape(-1,a.shape[1])
print(b)

Output:

[[0 6 7 9 1]
 [0 6 7 9 1]
 [0 6 7 9 1]
 [2 4 6 2 7]
 [2 4 6 2 7]
 [2 4 6 2 7]]
  • Related