在多维numpy数组的每个索引处切片不同的范围 [英] Slicing a different range at each index of a multidimensional numpy array
问题描述
我有一个m
x n
numpy数组arr
,对于arr
的每一列,我都有要访问的给定行范围.
我有一个n
x 1
数组vec
,它描述了该范围的开始时间.
该范围具有一定的持续时间d
.
I have an m
x n
numpy array arr
, and for each column of arr
, I have a given range of rows that I want to access.
I have an n
x 1
array vec
that describes when this range starts.
The range has some constant duration d
.
如何有效地提取感兴趣的d
x n
数组?
可以通过巧妙的切片来完成吗?
How can I extract this d
x n
array of interest efficiently?
Can this be done by clever slicing?
我最初的想法是尝试类似的事情:
My initial thought was to try something like:
arr = np.tile(np.arange(10),(4,1)).T
vec = np.array([3,4,5,4])
d = 3
vec_2 = vec+d
out = arr[vec:vec2,np.arange(n)]
但这会导致以下错误:
TypeError:只有整数标量数组可以转换为标量索引
TypeError: only integer scalar arrays can be converted to a scalar index
所需的输出将是以下数组:
The desired output would be the following array:
array([[3, 4, 5, 4],
[4, 5, 6, 5],
[5, 6, 7, 6],
[6, 7, 8, 7])
我可以遍历d
,但是性能对于这段代码很重要,因此我希望将其向量化.
I could loop over d
, but performance is important for this piece of code so I would prefer to vectorize it.
推荐答案
In [489]: arr=np.arange(24).reshape(6,4)
In [490]: vec=np.array([0,2,1,3])
利用最近扩展的linspace
来生成多个数组:
Taking advantage of the recent expansion of linspace
to generate several arrays:
In [493]: x = np.linspace(vec,vec+2,3).astype(int)
In [494]: x
Out[494]:
array([[0, 2, 1, 3],
[1, 3, 2, 4],
[2, 4, 3, 5]])
In [495]: arr[x, np.arange(4)]
Out[495]:
array([[ 0, 9, 6, 15],
[ 4, 13, 10, 19],
[ 8, 17, 14, 23]])
列迭代方法:
In [498]: np.stack([arr[i:j,k] for k,(i,j) in enumerate(zip(vec,vec+3))],1)
Out[498]:
array([[ 0, 9, 6, 15],
[ 4, 13, 10, 19],
[ 8, 17, 14, 23]])
这篇关于在多维numpy数组的每个索引处切片不同的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!