Sunday, November 17, 2024
Google search engine
HomeLanguagesPython | Pandas Series.nonzero() to get Index of all non zero values...

Python | Pandas Series.nonzero() to get Index of all non zero values in a series

Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.

Pandas Series.nonzero() is an argument less method. Just like it name says, rather returning non zero values from a series, it returns index of all non zero values. The returned series of indices can be passed to iloc method and return all non zero values.

Syntax: Series.nonzero()
Return type: Array of indices

Example:
In this example, a Series is created from a Python List using Pandas Series() method. The series also contains some zero values. After that nonzero() method is called on series and the result is stored in result variable. The result series is then passed to iloc() method to return all non zero values at that indices.




# importing pandas module 
import pandas as pd 
    
# importing numpy module 
import numpy as np 
    
# creating list
list =[1, 0, 12, 1, 0, 4, 22, 0, 3, 9]
  
# creating series
series = pd.Series(list)
  
# calling .nonzero() method
result = series.nonzero()
  
# display
print(result)
  
# retrieving values using iloc method
values = series.iloc[result]
  
# display
values


Output:

(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 output, the index position of every non zero elements was returned and the values at that position were returned using iloc method.

RELATED ARTICLES

Most Popular

Recent Comments