How to transform every element of numpy array into an array of size N filled with the element?

Question:

I have a numpy array a the shape of which is (m, n).
I want to transform this array into an array b with shape (m, n, l), where:

b[i,j].length == l
b[i,j,k] == a[i,j]

0 <= i < m
0 <= j < n
0 <= k < l

For example:

m = 2
n = 3
a = [[1,2,3],[4,5,6]]

If l = 2, then b:

b = [[[1,1],[2,2],[3,3]],[[4,4],[5,5],[6,6]]]

How can I do it? Is there an easy one-line solution?

Asked By: g00dds

||

Answers:

This does it:

np.repeat(a, l).reshape(a.shape + (-1,))
Answered By: John Zwinck
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.