0

Given arr1 = [[0,0,0,0],[0,0,0,0],[0,0,0,0] and arr2 = [[1,2],[3,4],[4,5]] and positions = [0,1,2] we wish to add elements of arr2 to elements of elements of arr1 at the indices specified by postions that is our answer should be [[1,2,0,0],[0,3,4,0],[0,0,4,5]] Note that we guarantee beforehand that the position would be valid.

A simple for loop over the outer array solution works but is pretty slow for my application. I tried using splicing and specifing positions but nothing seems to work.

2 Answers2

1

You haven't really defined your existing solution, but the simple, straightforward way would be something like:

>>> arr1 = [[0,0,0,0],[0,0,0,0],[0,0,0,0]]
>>> arr2 = [[1,2],[3,4],[4,5]]
>>> positions = [0,1,2]
>>> for sub, items, pos in zip(arr1, arr2, positions):
...     sub[pos: pos + len(items)] = items
...
>>> arr1
[[1, 2, 0, 0], [0, 3, 4, 0], [0, 0, 4, 5]]

If mutating the sublists in arr1 is fine, this should be pretty much the fastest solution in vanilla python.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
1

If making it with numpy you'd still need to arrange indices (positions) and values (arr2) shapes. The following is solution using np.put_along_axis routine:

arr1 = np.array([[0,0,0,0],[0,0,0,0],[0,0,0,0]])
arr2 = [[1,2], [3,4], [4,5]]
pos = [0, 1, 2]
np.put_along_axis(arr1, np.array([np.arange(p, len(r)+p)
                                  for p, r in zip(pos, arr2)]), arr2, axis=1)
print(arr1)

[[1 2 0 0]
 [0 3 4 0]
 [0 0 4 5]]
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105