append a list at the end of each row of 2D array

孤街醉人 提交于 2020-06-14 07:35:47

问题


I want to append a list/1d array (b) at the end of each row of a 2d array (a)

input:

a = np.array([[1, 1], [2, 2], [3, 3]])
b = np.array([4, 4])

desired out:

array([[1, 1, 4, 4],
       [2, 2, 4, 4],
       [3, 3, 4, 4]])

my code:

temp = []
for i in range(len(a)):
   c = np.hstack((a[i], b))
   temp.append(c)
d = np.vstack(temp)

is there any better and fast solution for this.


回答1:


a = np.array([[1, 1], [2, 2], [3, 3]])
b = np.array([4, 4])

c = np.tile(b[np.newaxis,:], (a.shape[0],1))
d = np.concatenate((a,c), axis=1)


来源:https://stackoverflow.com/questions/25530223/append-a-list-at-the-end-of-each-row-of-2d-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!