Python | Pandas Series.nonzero () to get the index of all non-zero values ​​in a series



Pandas Series.nonzero() — it is a method with no arguments. As the name suggests, by returning non-zero values ​​from a series, it returns the index of all non-zero values. The returned series of indexes can be passed to the method iloc () to return all nonzero values ​​at those indices.

# pandas module import

import pandas as pd 

 
# numpy module import

import numpy as np 

 
# create a list

list = [ 1 , 0 , 12 , 1 , 0 , 4 , 22 , 0 , 3 , 9 ]

 
# create series

series = pd.Series ( list )

  
# calling the .nonzero () method

result = series.nonzero ()

 
# dis play

print (result)

 
# getting values ​​using the iloc method

values ​​ = series.iloc [result]

 
# display
values ​​

Exit:

 (array ([0, 2, 3, 5, 6 , 8, 9]),) 0 1 2 12 3 1 5 4 6 22 8 3 9 9 dtype: int64 

As shown in the output, the index position of each nonzero element was returned, and the values ​​in this positions were returned by the iloc method.