1

I want to do arithmetic operation on dynamically specified axis and index and update values at the original array for example:

import numpy as np

array = np.array([[[1, 2],
                   [3, 4],
                   [5, 6]],
                  [[7, 8],
                   [9, 10],
                   [11, 12]]])
axis = 1
indices = [0,2]

for example adding 1 to specified axis and indices, and get the new array as:

array = [[[2, 3],
          [3, 4],
          [6, 7]],
         [[8, 9],
          [9, 10],
          [12, 13]]])
  • I don't like trying to deduce what you are doing by comparing the two arrays. You should make it clear with working code - even if it isn't as fast or dynamic as you'd like. – hpaulj May 01 '20 at 16:15

3 Answers3

0
import numpy as np

array = np.array([[[1, 2],
                   [3, 4],
                   [5, 6]],
                  [[7, 8],
                   [9, 10],
                   [11, 12]]])
indices = [0, 2]

# either like this
array[:, indices, :] += 1

# or using a for loop
for idx in range(len(array)):  
   array[idx, indices, :] += 1

print(array)
mapf
  • 1,906
  • 1
  • 14
  • 40
  • It doesn't solve my problem; I want to dynamically change axis (dimension) in a loop – Amir Daghestani May 01 '20 at 09:35
  • I don't understand what you mean by that. – mapf May 01 '20 at 09:39
  • I am using a loop which axis value changes in each iteration, from 0 to len(array). for more clarification: in loop one, I have array[indices, : , :] += 1; in loop 2, I have array[:, indices, :] += 1; in loop 3, I have array[:, :, indices] += 1, and so forth for higher dimensions! – Amir Daghestani May 01 '20 at 09:45
0

if you want a loop use:

import numpy as np

array = np.array([[[1, 2],
                   [3, 4],
                   [5, 6]],
                  [[7, 8],
                   [9, 10],
                   [11, 12]]])
indices = [0, 2]

for i in array:
    i[[0, 2]] += 1
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

I got my answer in this post: Slicing a numpy array along a dynamically specified axis Just in my case:

def slicer(array, indices, axis):
    selection = [slice(None)] * array.ndim
    selection[axis] = indices
    return tuple(selection)

slice(None) is equivalent to :. Finally:

array[slicer(array, indices, axis)] += 1