Kind of new to python and I need to use numpy to append a column, I have an ndarray a with [[1 2 3] [4 5 6]] and another ndarray with b [1 7] so the end result should be [[1 2 3 1] [4 5 6 7] . I have tried
array = np.append(a , b, axis=1)
but I get
all the input arrays must have same number of dimensions
(makes sense). I was also trying to insert it in a for loop but based on what i have seen with python these libraries have an easy way to do things and I was wondering if there is a more efficient way?
1 Answer 1
Try numpy.hstack with added axis to b -
a = np.array([[1,2,3],[4,5,6]])
b = np.array([1,7])
np.hstack([a,b[:,None]])
array([[1, 2, 3, 1],
[4, 5, 6, 7]])
Notes:
b[:,None]adds an axis to turn b from 1D(2,)to 2D(2,1)array (its the same asb.reshape(-1,1))np.hstackis now able to horizontally stack(2,3)and(2,1)to give(2,4)shaped array
answered Jan 29, 2021 at 1:37
Akshay Sehgal
19.4k3 gold badges26 silver badges57 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
DunkRuZ
Ah I see thank you, and the resulting is another ndarray ? . and does it work with any array size and dimension? (for a forexample, b will always be 1D)
Akshay Sehgal
Depends. for np.hstack, you will need the first dimension to be common. as long as the number of rows in a and the number of elements in b are equal .. yes.
Akshay Sehgal
Do mark the answer if he solved your question :) It encourages me to help you again in the future!
lang-py