当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python numpy.nonzero()用法及代码示例


numpy.nonzero()function用于计算非零元素的索引。

它返回一个数组元组,每个数组对应arr维度,其中包含该维度中非零元素的索引。
数组中对应的非零值可以使用 arr[nonzero(arr)] 。要按元素而不是按维度对索引进行分组,我们可以使用 transpose(nonzero(arr))

用法: numpy.nonzero(arr)

参数:
arr :[数组]输入数组。

Return :[tuple_of_arrays]非零元素的索引。

代码1:工作

# Python program explaining 
# nonzero() function 
  
import numpy as geek 
arr = geek.array([[0, 8, 0], [7, 0, 0], [-5, 0, 1]]) 
  
print ("Input  array:\n", arr) 
    
out_tpl = geek.nonzero(arr) 
print ("Indices of non zero elements:", out_tpl) 

输出:

Input array:
[[ 0 8 0]
[ 7 0 0]
[-5 0 1]]
Indices of non zero elements: (array([0, 1, 2, 2], dtype=int64), array([1, 0, 0, 2], dtype=int64))


代码2:

# Python program for getting 
# The corresponding non-zero values:
out_arr = arr[geek.nonzero(arr)] 
  
print ("Output array of non-zero number:", out_arr) 

输出:

Output array of non-zero number: [ 8  7 -5  1]


代码3:

# Python program for grouping the indices 
# by element, rather than dimension 
  
out_ind = geek.transpose(geek.nonzero(arr)) 
  
print ("indices of non-zero number:\n", out_ind) 

输出:

indices of non-zero number:
 [[0 1]
 [1 0]
 [2 0]
 [2 2]]


相关用法


注:本文由纯净天空筛选整理自jana_sayantan大神的英文原创作品 numpy.nonzero() in Python。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。