w3resource

Pandas Series: str.count() function

Series-str.count() function

The str.count() function is used to count occurrences of pattern in each string of the Series/Index.

This function is used to count the number of times a particular regex pattern is repeated in each of the string elements of the Series.

Syntax:

Series.str.count(self, pat, case=True, flags=0, na=nan, regex=True)
Pandas Series: str.count() function

Parameters:

Name Description Type/Default Value Required / Optional
pat  Valid regular expression. str Required
flags  Flags for the re module. For a complete list, int, default 0, meaning no flags Required
**kwargs  For compatibility with other string methods. Not used.   Required

Returns: Series or Index
Same type as the calling object containing the integer counts.

Example:

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.Series(['P', 'Q', 'Abbi', 'Babi', np.nan, 'CBCA', 'bag'])
s.str.count('b')

Output:

0    0.0
1    0.0
2    2.0
3    1.0
4    NaN
5    0.0
6    1.0
dtype: float64

Example - Escape '$' to find the literal dollar sign:

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.Series(['$', 'Q', 'A$bi', '$a$i', 'C$CA', 'bag'])
s.str.count('\$')

Output:

0    1
1    0
2    1
3    2
4    1
5    0
dtype: int64
Pandas Series: str.count() function

Example - This is also available on Index:

Python-Pandas Code:

import numpy as np
import pandas as pd
pd.Index(['P', 'P', 'Abbi', 'bag']).str.count('b')

Output:

Int64Index([0, 0, 2, 1], dtype='int64')

Previous: Series-str.contains() function
Next: Series-str.endswith() function



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/pandas/series/series-str-count.php