1

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
1
  • b isn't a column. Commented Oct 17, 2020 at 11:57

3 Answers 3

4

You can do it like this:

np.hstack((a,b.reshape(2,1)))
array([[1, 2, 3, 5],
       [4, 5, 6, 6]])
Sign up to request clarification or add additional context in comments.

Comments

2

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]])

Comments

0

You can do it like this:

import numpy as np
a = np.array([[1,2,3], [4,5,6]])
b = np.array([5, 6])
c=np.concatenate([a,b[:,None]],axis=1)

2 Comments

This is exactly what has already been suggested in 2020. Please don't just duplicate existing answers, but only post if you can provide additional insights.
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.