Reputation: 3151
I have two arrays:
import numpy as np
a = np.array([[1,2,3], [4,5,6]])
b = np.array([5, 6])
when I try to append b
to a
as a
's last column using the below code
np.hstack([a, b])
it thows an error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<__array_function__ internals>", line 6, in hstack
File "C:\Users\utkal\anaconda3\envs\AIML\lib\site-packages\numpy\core\shape_base.py", line 345, in hstack
return _nx.concatenate(arrs, 1)
File "<__array_function__ internals>", line 6, in concatenate
ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 1 dimension(s)
I want the final array as:
1 2 3 5
4 5 6 6
Upvotes: 0
Views: 1555
Reputation: 25239
np.hstack
is a shortcut for np.concatenate
on axis=1. So, it requires both arrays have the same shapes with all dimensions matching except on concatenate axis. In your case, you need both array in 2-d and matching on dimension 0
So you need
np.hstack([a, b[:,None]])
Out[602]:
array([[1, 2, 3, 5],
[4, 5, 6, 6]])
Or use np.concatenate
np.concatenate([a, b[:,None]], axis=1)
Out[603]:
array([[1, 2, 3, 5],
[4, 5, 6, 6]])
Upvotes: 1
Reputation: 331
You can do it like this:
np.hstack((a,b.reshape(2,1)))
array([[1, 2, 3, 5],
[4, 5, 6, 6]])
Upvotes: 3