python - NumPy: 2D array from a list of arrays and scalars -


i need create 2d numpy array list of 1d arrays , scalars scalars replicated match length of 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 vectorial elements of list going have same length (shape) can "by hand" doing this:

def something(lst):     e in lst:         if isinstance(e, np.ndarray):             l = len(e)             break     tmp = []     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 asking whether there ready-made solution hidden somewhere in numpy or, if there none, whether there better (e.g. more general, more reliable, faster) solution 1 above.

in [179]: np.column_stack(np.broadcast(x, 0, x)) out[179]:  array([[ 1.,  1.,  1.,  1.,  1.],        [ 0.,  0.,  0.,  0.,  0.],        [ 1.,  1.,  1.,  1.,  1.]]) 

or

in [187]: np.row_stack(np.broadcast_arrays(x, 0, x)) out[187]:  array([[ 1.,  1.,  1.,  1.,  1.],        [ 0.,  0.,  0.,  0.,  0.],        [ 1.,  1.,  1.,  1.,  1.]]) 

using np.broadcast faster np.broadcast_arrays:

in [195]: %timeit np.column_stack(np.broadcast(*[x, 0, x]*10)) 10000 loops, best of 3: 46.4 µs per loop  in [196]: %timeit np.row_stack(np.broadcast_arrays(*[x, 0, x]*10)) 1000 loops, best of 3: 380 µs per loop 

but slower something function:

in [201]: %timeit something([x, 0, x]*10) 10000 loops, best of 3: 37.3 µs per loop 

note np.broadcast can passed @ 32 arrays:

in [199]: np.column_stack(np.broadcast(*[x, 0, x]*100)) valueerror: need @ least 2 , fewer (32) array objects. 

whereas np.broadcast_arrays unlimited:

in [198]: np.row_stack(np.broadcast_arrays(*[x, 0, x]*100)) out[198]:  array([[ 1.,  1.,  1.,  1.,  1.],        [ 0.,  0.,  0.,  0.,  0.],        [ 1.,  1.,  1.,  1.,  1.],        ...,         [ 1.,  1.,  1.,  1.,  1.],        [ 0.,  0.,  0.,  0.,  0.],        [ 1.,  1.,  1.,  1.,  1.]]) 

using np.broadcast or np.broadcast_arrays bit more general something. work on arrays of different (but broadcastable) shapes, instance:

in [209]: np.column_stack(np.broadcast(*[np.atleast_2d(x), 0, x])) out[209]:  array([[ 1.,  1.,  1.,  1.,  1.],        [ 0.,  0.,  0.,  0.,  0.],        [ 1.,  1.,  1.,  1.,  1.]]) 

whereas something([np.atleast_2d(x), 0, x]) returns:

in [211]: something([np.atleast_2d(x), 0, x]) out[211]:  array([array([[ 1.,  1.,  1.,  1.,  1.]]), array([ 0.]),        array([ 1.,  1.,  1.,  1.,  1.])], dtype=object) 

Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

Swift game error message -