# [Numpy-discussion] Only integer scalar arrays can be converted to a scalar index

Michael Bostock bostock83 at gmail.com
Thu Sep 14 04:36:14 EDT 2017

```Hi,

I am trying to do a slding window on a cube (3D array) to get the average
over a block of vertical 1D arrays. I have achieved this using the
stride_tricks.asstrided but this will load the whole cube into memory at
once and is not suitable for large cubes. I have also achieved it using an
nditer but this is a lot slower:

def trace_block(vol, x, y, half_window):
return vol[x - half_window:x + half_window + 1, y - half_window:y
+ half_window + 1]

vol = np.linspace(1, 125, 125, dtype=np.int32).reshape(5, 5, 5)
window_size = 3

x, y, z = vol.shape
half_window = (window_size - 1) // 2
xs = np.arange(half_window, x - half_window, dtype=np.int16)
ys = np.arange(half_window, y - half_window, dtype=np.int16)
averaged = np.zeros((5, 5, 5))
for x, y in np.nditer(np.ix_(xs, ys)):
averaged[x, y] = np.mean(trace_block(vol, x, y, half_window), (0, 1))

My attempt at using numpy vectorisation to avoid the for loop throws the
error in the subject:

vol = np.linspace(1, 125, 125, dtype=np.int32).reshape(5, 5, 5)
window_size = 3

x, y, z = vol.shape
half_window = (window_size - 1) // 2
xs = np.arange(half_window, x - half_window, dtype=np.int16)
ys = np.arange(half_window, y - half_window, dtype=np.int16)
averaged = np.zeros((5, 5, 5))
xi, yi = np.ix_(xs, ys)
averaged[xi, yi] = np.mean(trace_block(vol, xi, yi, half_window), (0, 1))

Is there any way to do slicing as shown in the trace_block function to
support the xi and yi grid arrays?