Shortest code to repeat array([x,y,z]) in Python

Viewed 119

What is the shortest code to repeat numpy array([x,y,z]) and make array([[x,y,z], [x,y,z], [x,y,z], ...]) which to make the code like shown below:

import numpy as np
p = np.array([1, 2, 3])
n = 10
p_n = np.tile(p, n).reshape(n, 3)

output of the code:

array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3],
       [1, 2, 3],
       [1, 2, 3],
       [1, 2, 3],
       [1, 2, 3],
       [1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]])
4 Answers

Your code works pretty well. I don't see the point of shorten few characters.

That said here's a (few-character) shorter option

p_n = np.vstack([p]*n)

Note: avoid from numpy import *. Numpy has too many things and it may break some of Python's default functionalities (e.g. bool)

If you already have an array prepared which stores the repeated coordinates, then this is short enough:

p_n[:] = p

It's helpful if you assign to p_n multiple times.

You can also use np.repeat, for example

np.repeat(np.arange(3)[None,:],4,axis=0)

Given array p and scaling number n, shortest one would be (without any function to help it make it a short one) -

p_n = p+[[0]]*n

Sample run -

In [17]: p+[[0]]*n
Out[17]: 
array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3],
       [1, 2, 3],
       [1, 2, 3],
       [1, 2, 3],
       [1, 2, 3],
       [1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]])
Related