Reputation: 199
I am trying to concatenate a 1D into a 2D array. I'd like to avoid doing a loop as it's very computer intensive if my array lengths are greater than 1000.
I have tried vstack, stack and concatenate with no success.
import numpy as np
array_a = np.array([1,2,3])
array_b = np.array([[10, 11, 12], [20, 21, 22], [30, 31, 32]])
The expected output should be
array([[1, 10, 11, 12], [2, 20, 21, 22], [3, 30, 31, 32]])
Many thanks for your help!
Upvotes: 1
Views: 105
Reputation: 231605
Mykola showed the right way to do this, but I suspect you need a little help in understanding why. You tried several things without telling us what was wrong.
In [241]: array_a = np.array([1,2,3])
...: array_b = np.array([[10, 11, 12], [20, 21, 22], [30, 31, 32]])
vstack
runs:
In [242]: np.vstack((array_a, array_b))
Out[242]:
array([[ 1, 2, 3],
[10, 11, 12],
[20, 21, 22],
[30, 31, 32]])
But the result is a vertical join, by rows, not columns. The v
in vstack
is supposed to remind us of that.
stack
tries to join the arrays on a new axis, and requires that all input array have a matching shape:
In [243]: np.stack((array_a, array_b))
...
ValueError: all input arrays must have the same shape
I suspect you tried this at random, without really reading the docs.
Both of these use concatenate
, which is the basic joiner. But it's picky about dimensions:
In [244]: np.concatenate((array_a, array_b))
...
ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 1 dimension(s) and the array at index 1 has 2 dimension(s)
You clearly realized that the number of dimensions didn't match.
You want to make a (3,4) array. One is (3,3), the other needs to be (3,1). And join axis needs to be 1
In [247]: np.concatenate((array_a[:,None], array_b), axis=1)
Out[247]:
array([[ 1, 10, 11, 12],
[ 2, 20, 21, 22],
[ 3, 30, 31, 32]])
If we made a (1,3) array, and tried to join on the default 0 axis, we get the same thing as the vstack
. In fact that's what vstack
does:
In [248]: np.concatenate((array_a[None,:], array_b))
Out[248]:
array([[ 1, 2, 3],
[10, 11, 12],
[20, 21, 22],
[30, 31, 32]])
Another function is:
In [249]: np.column_stack((array_a, array_b))
Out[249]:
array([[ 1, 10, 11, 12],
[ 2, 20, 21, 22],
[ 3, 30, 31, 32]])
This does the same thing as [247].
Functions like vstack
and column_stack
are handy, but in long run it's better to understand how to use concatenate
itself.
Upvotes: 3
Reputation: 17882
You can reshape()
the first array and then concatenate()
both arrays:
np.concatenate([array_a.reshape(3, -1), array_b], axis=1)
Upvotes: 2
Reputation: 61920
You want insert:
import numpy as np
array_a = np.array([1, 2, 3])
array_b = np.array([[10, 11, 12], [20, 21, 22], [30, 31, 32]])
result = np.insert(array_b, 0, array_a, axis=1)
print(result)
Output
[[ 1 10 11 12]
[ 2 20 21 22]
[ 3 30 31 32]]
Upvotes: 2