Numpy slicing with bound checks

前端 未结 2 386
渐次进展
渐次进展 2020-12-20 17:46

Does numpy offer a way to do bound checking when you slice an array? For example if I do:

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

This sli

2条回答
  •  一向
    一向 (楼主)
    2020-12-20 18:29

    If you used range instead of the common slicing notation you could get the expected behaviour. For example for a valid slicing:

    arr[range(2),:]
    
    array([[1., 1.],
           [1., 1.]])
    

    And if we tried to slice with for instance:

    arr[range(5),:]
    

    It would throw the following error:

    IndexError: index 2 is out of bounds for size 2

    My guess on why this throws an error is that slicing with common slice notation is a basic property in numpy arrays as well as lists, and thus instead of throwing an index out of range error when we try to slice with wrong indices, it already contemplates this and cuts to the nearest valid indices. Whereas this is apparently not contemplated when slicing with a range, which is an immutable object.

提交回复
热议问题