Expanding a vector by replicating elements individually

Terry Reedy tjreedy at udel.edu
Wed Sep 22 19:30:47 CEST 2010


On 9/21/2010 11:03 PM, gburdell1 at gmail.com wrote:
> Given
>
> m=numpy.array([[1, 2, 3]])
>
> I want to obtain
>
> array([[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]])
>
> One way I've found to do this is:
>
> numpy.reshape(numpy.tile(m,(4,1)),(12,1),'f').T
>
> Another way is:
>
> numpy.reshape(numpy.tile(m,(4,1)).flatten(1),(1,12))
>
> Is there a simpler way to do this, without having to go jump through
> so many hoops?

With a Python list
 >>> l = []
 >>> for rep in [[i]*4 for i in [1,2,3]]:
	l.extend(rep)
	
 >>> l
[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]

or
 >>> list(chain(*[[i]*4 for i in [1,2,3]]))
[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]

Can you adapt that with numpy.array instead of list? Might be slower though
-- 
Terry Jan Reedy




More information about the Python-list mailing list