Reputation: 591
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?
Upvotes: 2
Views: 736
Reputation: 114440
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)
Upvotes: 0
Reputation: 2816
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]))
Upvotes: 2