I need to specialized numpy arrays. Assume I have a function:
def gen_array(start, end, n_cols):
It should behave like this, generating three columns where each column goes from start (inclusive) to end (exclusive):
>>> gen_array(20, 25, 3)
array([[20, 20, 20],
[21, 21, 21],
[22, 22, 22],
[23, 23, 23],
[24, 24, 24]])
My rather naïve implementation looks like this:
def gen_array(start, end, n_columns):
a = np.arange(start, end).reshape(end-start, 1) # create a column vector from start to end
return np.dot(a, [np.ones(n_columns)]) # replicate across n_columns
(It's okay, though not required, that the np.dot converts values to floats.)
I'm sure there's a better, more efficient and more numpy-ish way to accomplish the same thing. Suggestions?
Update
Buildin on a suggestion by @msi_gerva to use np.tile, my latest best thought is:
def gen_array(start, end, n_cols):
return np.tile(np.arange(start, end).reshape(-1, 1), (1, n_cols))
... which seems pretty good to me.
a = np.tile(np.arange(20,25,1),(3,1)).T. Not very elegant (using transpose in the end), but at least a one-liner.tilelooks good - How about reshaping first:a = np.tile(np.arange(20,25)).reshape(-1,1), (1, 3))dotjust multiply,a * np.ones(n_columns). That's a (5,1) times a (3,) broadcasting to (5,3).