How to stack arrays and scalars in numpy?

I have a list of number vectors (1-D arrays) or scalars (i.e. just numbers). All vectors are the same length, but I do not know what it is. I need vstackall elements to create one matrix (2-D array) so that scalars are considered as vectors having a scalar at each position.

An example is the best description:

Case 1:

>>> np.vstack([np.array([1, 2, 3]), np.array([3, 2, 1])])
array([[1, 2, 3],
       [3, 2, 1]])

Case 2:

>>> np.vstack([1, 2])
array([[1],
       [2]])

Case 3:

>>> np.vstack([np.array([1, 2, 3]), 0, np.array([3, 2, 1])])
np.array([[1, 2, 3],
          [0, 0, 0],
          [3, 2, 1]])

Cases 1 and 2 work out of the box. In case 3, however, this is not the case as vstack requires that all elements be arrays of the same length.

Is there any good way (preferably single line) to achieve this?

+4
source share
3 answers

np.column_stack :

In [175]: np.column_stack(np.broadcast([1, 2, 3], 0, [3, 2, 1]))
Out[175]: 
array([[1, 2, 3],
       [0, 0, 0],
       [3, 2, 1]])

NumPy :

In [158]: np.broadcast_arrays([1, 2, 3], [3, 2, 1], 0)
Out[158]: [array([1, 2, 3]), array([3, 2, 1]), array([0, 0, 0])]

vstack row_stack, :

In [176]: np.row_stack(np.broadcast_arrays([1, 2, 3], 0, [3, 2, 1]))
Out[176]: 
array([[1, 2, 3],
       [0, 0, 0],
       [3, 2, 1]])

( np.broadcast np.broadcast_arrays), np.broadcast , .

np.broadcast , 32 . np.broadcast_arrays.

+7

, python numpy.

, python , numpy . l=[ randint(10) if n%2 else randint(0,10,100) for n in range(32)]:

In [11]: %timeit array([x if type(x) is ndarray else [x]*100 for x in l])
1000 loops, best of 3: 655 µs per loop

In [12]: %timeit column_stack(broadcast(*l))
100 loops, best of 3: 3.77 ms per loop

, 32 .

+1

, .

>>> a = np.empty(4, dtype=int )
>>> a.fill(2)
>>> print(a)
[2 2 2 2]
0