Skip to content Skip to sidebar Skip to footer

Slicing A Different Range At Each Index Of A Multidimensional Numpy Array

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

Solution 1:

In [489]: arr=np.arange(24).reshape(6,4)                                                         
In [490]: vec=np.array([0,2,1,3])                                                                

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

the column iteration approach:

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

Post a Comment for "Slicing A Different Range At Each Index Of A Multidimensional Numpy Array"