Pandas Series - count() function
The Pandas Series count() function is used to count non-NA/null observations in the Series. The values None, NaN, NaT, and optionally pandas.inf (depending on pandas.options.mode.use_inf_as_na) are considered NA.
Syntax
Series.count(level=None)
Parameters
level |
Optional. Specify level (int or str). If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a smaller Series. A str specifies the level name. |
Return Value
Returns int or Series (if level specified), indicating number of non-null values in the Series.
Example: using count() on a Series
In the example below, the count() function is used to get the count of non-NA values in the series.
import pandas as pd import numpy as np idx = pd.MultiIndex.from_arrays([ ['even', 'even', 'even', 'odd', 'odd', 'odd']], names=['DataType']) x = pd.Series([10, 20, np.NaN, 5, np.NaN, np.NaN], name='Numbers', index=idx) print("The Series contains:") print(x) print("\nCount of non-NA values", x.count()) print("\nCount of non-NA values with level='DataType':\n", x.count(level='DataType')) print("\nCount of non-NA values with level=0:\n", x.count(level=0))
The output of the above code will be:
The Series contains: DataType even 10.0 even 20.0 even NaN odd 5.0 odd NaN odd NaN Name: Numbers, dtype: float64 Count of non-NA values 3 Count of non-NA values with level='DataType': DataType even 2 odd 1 Name: Numbers, dtype: int64 Count of non-NA values with level=0: DataType even 2 odd 1 Name: Numbers, dtype: int64
Example: using count() on selected series in a DataFrame
Similarly, the count() function can be applied on selected series/column of a given DataFrame. Consider the following example.
import pandas as pd import numpy as np info = pd.DataFrame({ "Person": ["John", "Mary", "Jo", "Sam"], "Age": [25, 24, 30, 28], "Bonus": ["10K", np.nan, "10K", "9K"] }) print(info) #using count on 'Person' series print("\ncount on Person returns:") print(info['Person'].count())
The output of the above code will be:
Person Age Bonus 0 John 25 10K 1 Mary 24 NaN 2 Jo 30 10K 3 Sam 28 9K count on Person returns: 4
❮ Pandas Series - Functions