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

…衆ロ難τιáo~ 提交于 2019-12-11 06:56:11

问题


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).


回答1:


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]])


来源:https://stackoverflow.com/questions/40345461/multiple-indices-for-numpy-array-indexerror-failed-to-coerce-slice-entry-of-ty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!