You could create broadcast object, and call np.column_stack on that:
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]])
Alternatively, you could ask NumPy to literally broadcast the items to compatibly-shaped arrays:
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])]
and then call vstack or row_stack on that:
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]])
Of these two options (using np.broadcast or np.broadcast_arrays),
np.broadcast is quicker since you don't actually need to instantiate the
broadcasted sub-arrays.
One limitation of np.broadcast, however, is that it can accept at most 32
arguments. In that case, use np.broadcast_arrays.
You could create broadcast object, and call np.column_stack on that:
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]])
Alternatively, you could ask NumPy to literally broadcast the items to compatibly-shaped arrays:
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])]
and then call vstack or row_stack on that:
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]])
Of these two options (using np.broadcast or np.broadcast_arrays),
np.broadcast is quicker since you don't actually need to instantiate the
broadcasted sub-arrays.
One limitation of np.broadcast, however, is that it can accept at most 32
arguments. In that case, use np.broadcast_arrays.
The problem here is to fill the gap between the readable python world, and the efficient numpy world.
Experimentally, python is paradoxically often better that numpy for this task. With 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
Furthermore broadcast is limited to 32 elements.
You can get the same with:
import numpy as np
a = np.arange(7, 13).reshape(2, 3)
b = np.arange(1, 7).reshape(2, 3)
z = np.stack((a, b), axis=1)
print(z)
# [[[ 7 8 9]
# [ 1 2 3]]
#
# [[10 11 12]
# [ 4 5 6]]]
You can use the numpy.row_stack method as follows:
a = np.arange(7, 13).reshape(2, 3)
b = np.arange(1, 7).reshape(2, 3)
x = np.row_stack((a[0],b[0]))
y = np.row_stack((a[1],b[1]))
z = np.row_stack([x, y])
Cheers.