了解NumPy的非零函数 [英] Understanding NumPy's nonzero function

查看:81
本文介绍了了解NumPy的非零函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解numpy的nonzero函数.以下是示例应用程序:

I am trying to understand numpy's nonzero function. The following is an example application:

import numpy
arr = numpy.array([[1,0],[1,1]])
arr.nonzero()
--> (array([0, 1, 1]), array([0, 0, 1]))

我可以看到,因为arr是2-D,所以nonzero()的输出是2元组.但是,我不明白为什么元组的每个元素中的索引数都超过了数组的行数/列数.我可以看到

I can see that because arr is 2-D, the output of nonzero() is a 2-tuple. However, I do not understand why the number of indices in each element of the tuple exceeds the number of rows/columns of the array. I can see that

arr[arr.nonzero()]
--> array([1, 1, 1])

但是怎么...?

推荐答案

元组的每个元素都包含每个非零值的索引之一.因此,每个元组元素的长度是数组中非零的数量.

Each element of the tuple contains one of the indices for each nonzero value. Therefore, the length of each tuple element is the number of nonzeros in the array.

在您的示例中,非零的索引为[0, 0][1, 0][1, 1].元组的第一个元素是每个非零值([0, 1, 1])的第一个索引,元组的第二个元素是每个非零值([0, 0, 1])的第二个索引.

From your example, the indices of the nonzeros are [0, 0], [1, 0], and [1, 1]. The first element of the tuple is the first index for each of the nonzero values: ([0, 1, 1]), and the second element of the tuple is the second index for each of the nonzero values: ([0, 0, 1]).

您的第二个代码块仅返回数组的非零值(我不清楚问题是否是返回值).

Your second code block just returns the nonzero values of the array (I am not clear from the question if the return value is part of the confusion).

>>> arr[arr.nonzero()]
array([1, 1, 1])

如果我们将示例数组与其他值一起使用,则更加清楚.

This is more clear if we use an example array with other values.

>>> arr = numpy.array([[1,0],[2,3]])
>>> arr[arr.nonzero()]
array([1, 2, 3])

这篇关于了解NumPy的非零函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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