Reputation: 123
I'm learning python and I have 2 arrays:
a = [[ 1 , 2 ]
[3, 4]]
b = [ 6,7]
when I print the shapes I get:
a.shape = (2,2)
b.shape = (2,)
want result to be:
c = [[ 1, 2 , 6]
[3, 4, 7]]
I've tried
c = a + b
and
c = np.concatenate((a, b),axis=None) #tried axis=0, axis=1
I keep getting errors like
ValueError: all the input arrays must have same number of dimensions
Upvotes: 1
Views: 164
Reputation: 231355
In [868]: a = np.array([[1,2],[3,4]]); b = np.array([6,7])
In [869]: a.shape, b.shape
Out[869]: ((2, 2), (2,))
b
has 1 dimension, it needs 2 to match a
:
In [870]: np.reshape(b,(2,1))
Out[870]:
array([[6],
[7]])
Now concatenate
works:
In [871]: np.concatenate((a, np.reshape(b,(2,1))), axis=1)
Out[871]:
array([[1, 2, 6],
[3, 4, 7]])
np.vstack
works because it adds a new initial dimension if needed. I added a trailing dimension.
In the long run to use concatenate
effectively you must learn about dimensions, and how to adjust them if needed.
Upvotes: 0
Reputation: 86168
You can use numpy.vstack
In [22]: import numpy as np
In [23]: a = np.array([[1,2], [3,4]])
In [24]: b = np.array([6,7])
In [25]: np.vstack((a.T, b)).T
Out[25]:
array([[1, 2, 6],
[3, 4, 7]])
Upvotes: 0
Reputation: 18208
May be you can try as shown in numpy example but b
needs to be of shape (1, 2)
by just adding array as a inner element of array: np.array([[6,7]])
a = np.array([[1, 2 ],
[3, 4]])
b = np.array([[6,7]])
c = np.concatenate((a, b.T), axis=1)
Output:
[[1 2 6]
[3 4 7]]
Upvotes: 1