Insert more than one value per row at index

允我心安 提交于 2020-04-11 04:24:22

问题


I am trying to vectorize the following operation:

  • Place a smaller array into a bigger array, whereby the index changes as a function of another array for each row.

Example data:

array_large = [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]] 
array_small = [[1,2],[3,4],[5,6]] 

array_index = [[1],[0],[2]] #*random index

Desired output: array_combined = [[0,1,2,0,0],[3,4,0,0,0],[0,0,5,6,0]]

So far I have been getting it to work with apply_along_axis - but I am wondering if there is a more efficient way of solving the problem. I can't seem to wrap my head around the indexing necessary to solve the problem.


回答1:


We can use advanced indexing here:

array_large[np.arange(array_large.shape[0])[:,None], array_index+[0,1]] = array_small

Or better, generalizing for whatever shape array_small may have:

i = np.arange(array_large.shape[0])[:,None]
j = array_index+np.arange(array_small.shape[1])
array_large[i,j] = array_small

print(array_large)

array([[0, 1, 2, 0, 0],
       [3, 4, 0, 0, 0],
       [0, 0, 5, 6, 0]])


来源:https://stackoverflow.com/questions/61102939/insert-more-than-one-value-per-row-at-index

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