Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
90 views
in Technique[技术] by (71.8m points)

python - Numpy array adding a column

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?

question from:https://stackoverflow.com/questions/65947622/numpy-array-adding-a-column

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

  1. b[:,None] adds an axis to turn b from 1D (2,) to 2D (2,1) array (its the same as b.reshape(-1,1))
  2. np.hstack is now able to horizontally stack (2,3) and (2,1) to give (2,4) shaped array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...