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:
- Replace
0.
values withNaN
- Create cumulative array (time = 0, x = x0, y = y0 -> time = 1, x = x0 + x1, y = y0 + y1) etc.
- 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]
?