获取数组中零和非零元素的索引 [英] Getting indices of both zero and nonzero elements in array

查看:258
本文介绍了获取数组中零和非零元素的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到数组的零个和非零元素的索引.

I need to find the indicies of both the zero and nonzero elements of an array.

换一种说法,我想从numpy.nonzero()中找到互补索引.

Put another way, I want to find the complementary indices from numpy.nonzero().

我知道的方法如下:

indices_zero = numpy.nonzero(array == 0)
indices_nonzero = numpy.nonzero(array != 0)

但是,这意味着搜索阵列两次,这对于大型阵列而言效率不高.有没有一种有效的方法可以使用numpy做到这一点?

This however means searching the array twice, which for large arrays is not efficient. Is there an efficient way to do this using numpy?

推荐答案

假定您已经具有使用范围numpy.arange(len(array)),只需获取并存储逻辑索引即可:

Assuming you already have the range for use numpy.arange(len(array)), just get and store the logical indices:

bindices_zero = (array == 0)

然后,当您实际需要整数索引时,就可以这样做

then when you actually need the integer indices you can do

indices_zero = numpy.arange(len(array))[bindices_zero]

indices_nonzero = numpy.arange(len(array))[~bindices_zero]

这篇关于获取数组中零和非零元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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