nickpick - 1 year ago 346
Python Question

# Multiple indices for numpy array: IndexError: failed to coerce slice entry of type numpy.ndarray to integer

Is there a way to do multiple indexing in a numpy array as described below?

``````arr=np.array([55, 2, 3, 4, 5, 6, 7, 8, 9])
arr[np.arange(0,2):np.arange(5,7)]

output:
IndexError: too many indices for array

Desired output:
array([55,2,3,4,5],[2,3,4,5,6])
``````

This problem might be similar to calculating a moving average over an array (but I want to do it without any function that is provided).

Here's an approach using `strides` -

``````start_index = np.arange(0,2)
L = 5     # Interval length
n = arr.strides[0]
strided = np.lib.stride_tricks.as_strided
out = strided(arr[start_index[0]:],shape=(len(start_index),L),strides=(n,n))
``````

Sample run -

``````In [976]: arr
Out[976]: array([55, 52, 13, 64, 25, 76, 47, 18, 69, 88])

In [977]: start_index
Out[977]: array([2, 3, 4])

In [978]: L = 5

In [979]: out
Out[979]:
array([[13, 64, 25, 76, 47],
[64, 25, 76, 47, 18],
[25, 76, 47, 18, 69]])
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download