带有约束检查的块状切片 [英] Numpy slicing with bound checks

查看:79
本文介绍了带有约束检查的块状切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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,:]

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

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

This slice will be okay and it will just return me the entire of arr even though I asked for indexes that don't exist. Is there another way to slice in numpy that will throw an error if I try to slice out of the bounds of an array?

推荐答案

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

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

它将引发以下错误:

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

IndexError: index 2 is out of bounds for size 2

我对为什么会引发错误的猜测是,使用普通切片符号进行切片是numpy数组以及列表中的基本属性,因此,当我们尝试使用错误切片时,不要抛出索引超出范围错误索引,它已经考虑到了这一点,并削减到最接近的有效索引.显然,在与range切片时并没有考虑到这一点,这是一个不可变的对象.

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.

这篇关于带有约束检查的块状切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆