Change language

Numpy recarray.nonzero () function | python

| | |

numpy.recarray.nonzero() is used to get the indices of non-zero elements in an array of records. It returns a tuple of arrays, one for each dimension arr, containing the indices of the nonzero elements in that dimension.

Syntax: numpy.recarray.nonzero ()

Parameters: None

Return: [tuple_of_arrays] Indices of elements that are non-zero.

Code # 1:

# Python program explaining
# numpy.recarray.nonzero () method

 
# import numy as geek

import numpy as geek

 
# create an input array with two different fields

in_arr = geek.array ([[( 0.0 , 2 ), ( 3.0 , - 4 ), ( 0.0 , 9 )],

[( 9.0 , 1 ), ( 5.0 , 0 ), ( - 12.0 , - 7 )]],

dtype = [( ’a’ , float ), ( ’b’ , int )])

 

print ( "Input array:" , in_arr)

 
# convert it to an array of posts,
# using arr.view (np.recarray)

rec_arr = in_arr.view (geek.recarray)

print ( "Record array of float:" , rec_arr.a) < / code>

print ( "Record array of int: " , rec_arr.b)

  
# using recarray.nonzero methods
# float array of records

out_arr = rec_arr.a.nonzero ()

print ( "Indices of non zero elements:" , out_arr) 

 
# applying recarray.nonzero methods
# to array of int entries

out_arr = rec_arr.b.nonzero ()

print ( " Indices of non zero elements: " , out_arr) 

Output:

Input array: [[(0., 2) (3., -4) (0., 9)]
[(9., 1) (5., 0) (-12., -7)]]
Record array of float: [[0. 3. 0.]
[9. 5. -12.]]
Record array of int: [[2 -4 9]
[1 0 -7]]
Indices of non zero elements: (array ([0, 1, 1, 1], dtype = int64), array ([1, 0, 1, 2], dtype = int64))
Indices of non zero elements: (array ([0, 0, 0, 1, 1], dtype = int64), array ([0, 1, 2, 0, 2], dtype = int64))

Code # 2:

We are applying numpy.recarray.nonzero () to the entire array of records.

# Python program explaining
# numpy.recarray.nonzero () method

  
# importing numy as a geek

import numpy as geek

 
# create input array with two different fields

in_arr = geek .array ([[( 5.0 , 2 ), ( 3.0 , 4 ), ( 6.0 , - 7 )],

  [( 9.0 , 1 ), ( 6.0 , 4 ), ( - 2.0 , - 7 )]],

dtype = [( ’a ’ , float ), ( ’b’ , int )])

 

print ( "Input array:" , in_arr)

 
# convert it to array of posts,
< code class = "comments"> # using arr.view (np.recarray)

rec_arr = in_arr.view (geek.recarray)

 
# using recarray.nonzero methods to write an array

out_arr = rec_arr.nonzero ()

 

print ( "Output array:" , out_arr)

Exit:

Input array: [[(5., 2) (3., 4) (6., -7)]
[(9., 1) (6., 4) (-2., -7) ]]
Output array: (array ([0, 0, 0, 1, 1, 1], dtype = int64), array ([0, 1, 2, 0, 1, 2], dtype = int64 ))