How to count the valid elements from a series object in Pandas?

PandasServer Side ProgrammingProgramming

The count() method in the pandas series is used to count the valid elements of a series object. This means it counts the number of non-null values of a series object.

This method takes only one parameter “level”, which takes an integer value for selecting the particular level of a MultiIndex object, by default the parameter value is None.

The output for this counting method is an integer value, which indicates the number of non-null values of a given series.

Example 1

import pandas as pd
import numpy as np

#create a pandas Series
series = pd.Series([18,23,44,32,np.nan,76,34,1,4,np.nan,21,34,90])

print(series)

print("apply count method: ",series.count())

Explanation

In this following example, we have created a pandas Series with a python list of integer values. And we applied the count() method to get the number of valid elements of the series.

Output

0  18.0
1  23.0
2  44.0
3  32.0
4   NaN
5  76.0
6  34.0
7   1.0
8   4.0
9   NaN
10 21.0
11 34.0
12 90.0
dtype: float64
apply count method: 11

The original series object has two NaN values and there are a total of 13 elements present in the series. The count() method only counts the valid elements of the series so that the output of the following example is 11.

Example 2

import pandas as pd
import numpy as np

#create a pandas Series
series = pd.Series([98,2,32,45,56])

print(series)

print("apply count method: ",series.count())

Explanation

Initially, we have created a pandas Series with a python list of integer values. After that, we calculated the total number of valid elements of the series by using the series.count() method.

Output

0 98
1  2
2 32
3 45
4 56
dtype: int64
apply count method: 5

For the following example, the number of valid elements is 5.

raja
Updated on 09-Mar-2022 07:49:24

Advertisements