带有约束检查的小块切片

时间:2019-02-11 14:03:00

标签: python numpy

在切片数组时,numpy是否提供一种进行边界检查的方法?例如,如果我这样做:

arr = np.ones([2,2]) sliced_arr = arr[0:5,:]

这片子没问题,即使我索要不存在的索引,它也只会返回整个arr。如果我尝试切出数组边界,还有另一种切入numpy的方法会引发错误吗?

2 个答案:

答案 0 :(得分:2)

如果使用range而不是常用的切片符号,则可以得到预期的行为。例如,有效的切片:

arr[range(2),:]

array([[1., 1.],
       [1., 1.]])

例如,如果我们尝试切片:

arr[range(5),:]

它将引发以下错误:

  

IndexError:索引2超出了大小2的范围

我对为什么会引发错误的猜测是,使用常见的切片符号进行切片是numpy数组以及列表中的基本属性,因此,当我们尝试切片时,不要抛出索引超出范围错误如果索引错误,它已经在考虑这一点并切到最接近的有效索引。显然,在与range切片时,这是无法预期的。

答案 1 :(得分:2)

结束的时间比预期的要长一点,但是您可以编写自己的包装程序来检查get操作,以确保切片不超出限制(不是切片的索引参数已由NumPy检查)。我想我在这里涵盖了所有情况(省略号,np.newaxis,否定步骤...),尽管可能还会出现一些失败的情况。

import numpy as np

# Wrapping function
def bounds_checked_slice(arr):
    return SliceBoundsChecker(arr)

# Wrapper that checks that indexing slices are within bounds of the array
class SliceBoundsChecker:

    def __init__(self, arr):
        self._arr = np.asarray(arr)

    def __getitem__(self, args):
        # Slice bounds checking
        self._check_slice_bounds(args)
        return self._arr.__getitem__(args)

    def __setitem__(self, args, value):
        # Slice bounds checking
        self._check_slice_bounds(args)
        return self._arr.__setitem__(args, value)

    # Check slices in the arguments are within bounds
    def _check_slice_bounds(self, args):
        if not isinstance(args, tuple):
            args = (args,)
        # Iterate through indexing arguments
        arr_dim = 0
        i_arg = 0
        for i_arg, arg in enumerate(args):
            if isinstance(arg, slice):
                self._check_slice(arg, arr_dim)
                arr_dim += 1
            elif arg is Ellipsis:
                break
            elif arg is np.newaxis:
                pass
            else:
                arr_dim += 1
        # Go backwards from end after ellipsis if necessary
        arr_dim = -1
        for arg in args[:i_arg:-1]:
            if isinstance(arg, slice):
                self._check_slice(arg, arr_dim)
                arr_dim -= 1
            elif arg is Ellipsis:
                raise IndexError("an index can only have a single ellipsis ('...')")
            elif arg is np.newaxis:
                pass
            else:
                arr_dim -= 1

    # Check a single slice
    def _check_slice(self, slice, axis):
        size = self._arr.shape[axis]
        start = slice.start
        stop = slice.stop
        step = slice.step if slice.step is not None else 1
        if step == 0:
            raise ValueError("slice step cannot be zero")
        bad_slice = False
        if start is not None:
            start = start if start >= 0 else start + size
            bad_slice |= start < 0 or start >= size
        else:
            start = 0 if step > 0 else size - 1
        if stop is not None:
            stop = stop if stop >= 0 else stop + size
            bad_slice |= (stop < 0 or stop > size) if step > 0 else (stop < 0 or stop >= size)
        else:
            stop = size if step > 0 else -1
        if bad_slice:
            raise IndexError("slice {}:{}:{} is out of bounds for axis {} with size {}".format(
                slice.start if slice.start is not None else '',
                slice.stop if slice.stop is not None else '',
                slice.step if slice.step is not None else '',
                axis % self._arr.ndim, size))

一个小演示:

import numpy as np

a = np.arange(24).reshape(4, 6)
print(bounds_checked_slice(a)[:2, 1:5])
# [[ 1  2  3  4]
#  [ 7  8  9 10]]
bounds_checked_slice(a)[:2, 4:10]
# IndexError: slice 4:10: is out of bounds for axis 1 with size 6

如果需要,甚至可以将其设置为subclass of ndarray,因此默认情况下会出现这种情况,而不必每次都包装数组。

此外,请注意,您可能认为“超出范围”可能会有一些变化。上面的代码认为即使超出一个索引也超出了范围,这意味着您不能使用arr[len(arr):]之类的空片。如果您认为行为略有不同,则原则上可以编辑代码。