Skip to main content
 首页 » 编程设计

python之最小尺寸包围 Numpy 数组(裁剪)

2024年09月07日7wayfarer

我想在包含满足条件的所有值的 ndarray 中找到最小大小的二维 ndarray。

例如: 假设我有数组

x = np.array([[1, 1, 5, 3, 11, 1], 
    [1, 2, 15, 19, 21, 33], 
    [1, 8, 17, 22, 21, 31], 
    [3, 5, 6,  11, 23, 19]]) 

并调用f(x, x % 2 == 0) 那么程序的返回值就是数组

[[2, 15, 19] 
 [8, 17, 22] 
 [5, 6, 11]] 

因为它是包含所有偶数的最小矩形数组(条件)。

我找到了一种方法,通过使用 np.argwhere 找到条件为真的所有索引,然后从原始数组的最小索引到最大索引进行切片,我已经使用 for 循环 完成它,但我想知道是否有更有效的方法使用 numpy 或 scipy 来完成它。

我目前的方法:

def f(arr, cond_arr): 
    indices = np.argwhere(cond_arr) 
    min = np.amin(indices, axis = 0) #get first row, col meeting cond 
    max = np.amax(indices, axis = 0) #get last row, col meeting cond 
    return arr[min[0]:max[0] + 1, min[1] : max[1] + 1] 

请您参考如下方法:

该功能已经非常高效 - 但您可以做得更好。

不是检查每一行/列的条件然后找到最小值和最大值,我们可以将条件折叠到每个轴(使用逻辑 OR 的归约)并找到第一个/最后一个索引:

def f2(arr, cond_arr): 
    c0 = np.where(np.logical_or.reduce(cond_arr, axis=0))[0] 
    c1 = np.where(np.logical_or.reduce(cond_arr, axis=1))[0]     
    return arr[c0[0]:c0[-1] + 1, c1[0]:c1[-1] + 1] 

工作原理:

示例数据 cond_array 如下所示:

>>> (x%2==0).astype(int) 
array([[0, 0, 0, 0, 0, 0], 
       [0, 1, 0, 0, 0, 0], 
       [0, 1, 0, 1, 0, 0], 
       [0, 0, 1, 0, 0, 0]]) 

这是列条件:

>>> np.logical_or.reduce(cond_arr, axis=0).astype(int) 
array([0, 1, 1, 1, 0, 0]) 

这是行条件:

>>> np.logical_or.reduce(cond_arr, axis=).astype(int) 
array([0, 1, 1, 1]) 

现在我们只需要为两个数组中的每一个找到第一个/最后一个非零元素。

真的更快吗?

%timeit f(x, x%2 == 0)   #  10000 loops, best of 3: 24.6 µs per loop 
%timeit f2(x, x%2 == 0)  # 100000 loops, best of 3: 12.6 µs per loop 

好吧,有一点点......但它确实在更大的阵列上闪耀:

x = np.random.randn(1000, 1000) 
c = np.zeros((1000, 1000), dtype=bool) 
c[400:600, 400:600] = True 
 
%timeit f(x,c)   #  100 loops, best of 3: 5.28 ms per loop 
%timeit f2(x,c)  # 1000 loops, best of 3: 225 µs per loop 

最后,此版本的开销略多,但在维数方面是通用的:

def f3(arr, cond_arr): 
    s = [] 
    for a in range(arr.ndim): 
        c = np.where(np.logical_or.reduce(cond_arr, axis=a))[0] 
        s.append(slice(c[0], c[-1] + 1)) 
    return arr[s]