0

I have some 3D and 4D arrays that I want to mutate. Indexing the arrays looks like:

  • 3D: array[time][x][y]
  • 4D: array[time][z][x][y]

I want to do multiple types of data mutation and have been writing a lot of for-in loops. Examples of data mutation:

  1. Replace 0. values with NaN
  2. Create cumulative array (time = 0, x = x0, y = y0 -> time = 1, x = x0 + x1, y = y0 + y1) etc.
  3. Use 2 arrays and combine them (sqrt(xa * xa + xb * xb)))

Numpy can be used for example to do (1) using:

for i in range(len(data)): 
    if len(data[i].shape) == 3:
        for z in range(len(data[i]):
            data[i][z][data[i][z] == 0.] = np.NaN
    else:
        data[i][data[i] == 0.] = np.NaN

But I have to write for loops every time I encounter such a problem and have to write the data mutation 2 times. Once for the 4D array and once for the 3D array. For-loops is a feature to overcome, not having to write if else statements and writing the mutation twice is almost a must. If I somehow or someone else changes the first part but forgets to change the second part the code becomes bugged.

Is there a way to for example enumerate the [z][x][y] but if the array is only [x][y] just do it once as if there was a single z-index like [0][x][y]?

Emptyless
  • 2,964
  • 3
  • 20
  • 30
  • Is http://stackoverflow.com/questions/24648045/dimensionality-agnostic-generic-cartesian-product helpful at all? – bouteillebleu May 05 '17 at 15:22
  • Not to my knowledge. I want some specific function that only affects the [x,y] part of the array without having to write it twice in separate loops. – Emptyless May 08 '17 at 10:51

0 Answers0