Numpy recarray.nonzero() function | Python
In numpy, arrays may have a data-types containing fields, analogous to columns in a spreadsheet. An example is [(a, int), (b, float)]
, where each entry in the array is a pair of (int, float). Normally, these attributes are accessed using dictionary lookups such as arr['a'] and arr['b']
. Record arrays allow the fields to be accessed as members of the array, using arr.a and arr.b
.
numpy.recarray.nonzero()
function is used to get the indices of the elements that are non-zero in the record array. It returns a tuple of arrays, one for each dimension of arr, containing the indices of the non-zero elements in that dimension.
Syntax : numpy.recarray.nonzero()
Parameters: None
Return : [tuple_of_arrays] Indices of elements that are non-zero.
Code #1 :
import numpy as geek
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)
rec_arr = in_arr.view(geek.recarray)
print ( "Record array of float: " , rec_arr.a)
print ( "Record array of int: " , rec_arr.b)
out_arr = rec_arr.a.nonzero()
print ( "Indices of non zero elements : " , out_arr)
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 whole record array.
import numpy as geek
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)
rec_arr = in_arr.view(geek.recarray)
out_arr = rec_arr.nonzero()
print ( "Output array : " , out_arr)
|
Output:
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))
Last Updated :
27 Sep, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...