本文介绍了numpy数组的多个索引:IndexError:无法将numpy.ndarray类型的切片条目强制转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一种方法可以在numpy数组中进行多个索引,如下所述?
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).
推荐答案
这是使用 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))
样品运行-
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]])
这篇关于numpy数组的多个索引:IndexError:无法将numpy.ndarray类型的切片条目强制转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!