检查一个numpy数组的所有边界是否都为0 [英] check if a numpy array has 0 on all its borders

查看:578
本文介绍了检查一个numpy数组的所有边界是否都为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检查多维numpy数组的所有面是否都为0的最快方法是什么.

What would be the fastest way to check if a multidimensional numpy array has 0 on all sides.

因此,对于一个简单的2D示例,我有:

So, for a simple 2D example, I have:

x = np.random.rand(5, 5)
assert np.sum(x[0:,  0]) == 0
assert np.sum(x[0,  0:]) == 0
assert np.sum(x[0:, -1]) == 0
assert np.sum(x[-1, 0:]) == 0

虽然对于2D情况来说这是可以的,但为更大的尺寸编写代码有点乏味,我想知道是否可以使用一些巧妙的numpy技巧来使它高效且可维护.

While this is ok for 2D cases to right, writing for higher dimensions is a bit tedious and I was wondering if there is some clever numpy trick I can use here to make it efficient and also more maintainable.

推荐答案

以下是您的操作方法:

assert(all(np.all(np.take(x, index, axis=axis) == 0)
           for axis in range(x.ndim)
           for index in (0, -1)))

np.take 的作用与花式"索引.

np.take does the same thing as "fancy" indexing.

这篇关于检查一个numpy数组的所有边界是否都为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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