Skip to main content
 首页 » 编程设计

python之在 Numpy 中切片索引的函数

2025年05月04日9jpfss

我有两个索引数组,我想返回它们之间的所有索引,就像一个切片函数,手动它看起来像这样:

ind1 = np.array([2,6]) 
ind2 = np.array([2,3]) 
 
final = np.array([[2,2,2], [4,5,6]]) 

由于切片的轴不固定,我想到了这个:

def index_slice(ind1,ind2): 
    return np.indices( 1 + ind1 - ind2 ) + ind2[:,np.newaxis,np.newaxis] 
 
final = index_slice(ind1,ind2) 

但是,这依赖于 1 + ind1 > ind2 并且它还包括最后一个索引(不是 pythonic)。有谁知道执行此操作的函数或更简洁的实现吗?
先感谢您。 迭戈

附言给出这个想法的来源背景。我正在考虑矩阵的子矩阵,我想从两个角的索引访问它们。由于问题的性质,给定的角并不总是与您在@pelson 的回答中看到的方向相同。

请您参考如下方法:

我没有把它放在一个衬里,但像下面这样的东西会重现你似乎要求的结果:

def index_slice(arr1, arr2): 
    lens = np.abs(arr1 - arr2) 
    if not all((lens == max(lens)) | (lens == 0)): 
        raise ValueError('The number of indices in some dimensions were inconsistent. Array lengths were %r' % lens) 
 
    max_len = lens.max() 
    result = np.empty((len(lens), max_len), dtype=np.int32) 
 
    for dim, (a, b) in enumerate(zip(arr1, arr2)): 
        if a == b: 
            result[dim, :] = a 
        elif a > b: 
            result[dim, :] = np.arange(a, b, -1) 
        else: 
            result[dim, :] = np.arange(a, b) 
 
    return result    

例如:

>>> ind1 = np.array([2, 6]) 
>>> ind2 = np.array([2, 3]) 
>>> print index_slice(ind1, ind2) 
[[2 2 2] 
 [6 5 4]] 
 
 
>>> ind1 = np.array([2, 6, 1]) 
>>> ind2 = np.array([2, 3, 4]) 
>>> print index_slice(ind1, ind2) 
[[2 2 2] 
 [6 5 4] 
 [1 2 3]] 

但是,问这个问题让我怀疑你可能正在做一些事情,如果你要分享你的上游逻辑,这些事情可以用更简单的方式完成。

HTH