I need to create a 2D numpy array from a list of 1D arrays and scalars so that the scalars are replicated to match the length of the 1D arrays.
Example of desired behaviour
>>> x = np.ones(5)
>>> something([x, 0, x])
array([[ 1., 1., 1., 1., 1.],
[ 0., 0., 0., 0., 0.],
[ 1., 1., 1., 1., 1.]])
I know that the vectorial elements of the list are always going to have the same length (shape) so I can do it "by hand" by doing something like this:
def something(lst):
for e in lst:
if isinstance(e, np.ndarray):
l = len(e)
break
tmp = []
for e in lst:
if isinstance(e, np.ndarray):
tmp.append(e)
l = len(e)
else:
tmp.append(np.empty(l))
tmp[-1][:] = e
return np.array(tmp)
What I am asking for is whether there is some ready-made solution hidden somewhere in numpy or, if there is none, whether there is a better (e.g. more general, more reliable, faster) solution than the one above.