What does count method do in the pandas series?

PandasServer Side ProgrammingProgramming

The count method in the pandas series will return an integer value, that value represents the total number of elements present in the series object. It counts only the valid element and neglects the invalid elements from series data.

Invalid elements are nothing but missing values like Nan, Null, and None. The count method won’t count missing values as an element, it will neglect the missing values and count the remaining values.

Example

# importing pandas packages
import pandas as pd

d = {'a':'A','c':"C",'d':'D','e':'E'}

#creating a series with null data
s_obj = pd.Series(d, index=list('abcdefg'))

print(s_obj)

# using count method
print('\nResult',s_obj.count())

Explanation

We have created a pandas series object using a python dictionary with text type elements, while creating the series object we have added some Nan data (Null values) by specifying the index attribute with new index labels. Those newly added index labels do not have any specific data so that it will create an empty element at that index position.

Output

a    A
b  NaN
c    C
d    D
e    E
f  NaN
g  NaN
dtype: object

Result 4

We can see the pandas series object ‘s_obj’ in the above output block. There are 7 index and value pairs with 3 missing values which are represented as NaN.

And we can see the output of the count method of pandas series in the above block, that is “Result 4”. It means, we have only 4 valid elements present in our series object s_obj, and the remaining all elements are invalid elements.

Example

# importing pandas packages
import pandas as pd
import numpy as np


#creating a series with null data
s_obj = pd.Series([2, 9, 6, None, 5, 9, np.nan])

print(s_obj)

# using count method
print('\nValues count:',s_obj.count())

Explanation

In this following example, we have created another pandas series object with some missing values using a python list. In that list, there are a total of 7 elements and two missing elements. One missing element is created by the python None keyword and another element is created by the NumPy attribute nan.

Output

0   2.0
1   9.0
2   6.0
3   NaN
4   5.0
5   9.0
6   NaN
dtype: float64

Values count: 5

We can see the output of both the series object ‘s_obj’ and count methods. Here there are 5 valid elements from the 7 element series object.

raja
Published on 17-Nov-2021 08:21:45
Advertisements