
- Python Pandas - Home
- Python Pandas - Introduction
- Python Pandas - Environment Setup
- Python Pandas - Basics
- Python Pandas - Introduction to Data Structures
- Python Pandas - Index Objects
- Python Pandas - Panel
- Python Pandas - Basic Functionality
- Python Pandas - Indexing & Selecting Data
- Python Pandas - Series
- Python Pandas - Series
- Python Pandas - Slicing a Series Object
- Python Pandas - Attributes of a Series Object
- Python Pandas - Arithmetic Operations on Series Object
- Python Pandas - Converting Series to Other Objects
- Python Pandas - DataFrame
- Python Pandas - DataFrame
- Python Pandas - Accessing DataFrame
- Python Pandas - Slicing a DataFrame Object
- Python Pandas - Modifying DataFrame
- Python Pandas - Removing Rows from a DataFrame
- Python Pandas - Arithmetic Operations on DataFrame
- Python Pandas - IO Tools
- Python Pandas - IO Tools
- Python Pandas - Working with CSV Format
- Python Pandas - Reading & Writing JSON Files
- Python Pandas - Reading Data from an Excel File
- Python Pandas - Writing Data to Excel Files
- Python Pandas - Working with HTML Data
- Python Pandas - Clipboard
- Python Pandas - Working with HDF5 Format
- Python Pandas - Comparison with SQL
- Python Pandas - Data Handling
- Python Pandas - Sorting
- Python Pandas - Reindexing
- Python Pandas - Iteration
- Python Pandas - Concatenation
- Python Pandas - Statistical Functions
- Python Pandas - Descriptive Statistics
- Python Pandas - Working with Text Data
- Python Pandas - Function Application
- Python Pandas - Options & Customization
- Python Pandas - Window Functions
- Python Pandas - Aggregations
- Python Pandas - Merging/Joining
- Python Pandas - MultiIndex
- Python Pandas - Basics of MultiIndex
- Python Pandas - Indexing with MultiIndex
- Python Pandas - Advanced Reindexing with MultiIndex
- Python Pandas - Renaming MultiIndex Labels
- Python Pandas - Sorting a MultiIndex
- Python Pandas - Binary Operations
- Python Pandas - Binary Comparison Operations
- Python Pandas - Boolean Indexing
- Python Pandas - Boolean Masking
- Python Pandas - Data Reshaping & Pivoting
- Python Pandas - Pivoting
- Python Pandas - Stacking & Unstacking
- Python Pandas - Melting
- Python Pandas - Computing Dummy Variables
- Python Pandas - Categorical Data
- Python Pandas - Categorical Data
- Python Pandas - Ordering & Sorting Categorical Data
- Python Pandas - Comparing Categorical Data
- Python Pandas - Handling Missing Data
- Python Pandas - Missing Data
- Python Pandas - Filling Missing Data
- Python Pandas - Interpolation of Missing Values
- Python Pandas - Dropping Missing Data
- Python Pandas - Calculations with Missing Data
- Python Pandas - Handling Duplicates
- Python Pandas - Duplicated Data
- Python Pandas - Counting & Retrieving Unique Elements
- Python Pandas - Duplicated Labels
- Python Pandas - Grouping & Aggregation
- Python Pandas - GroupBy
- Python Pandas - Time-series Data
- Python Pandas - Date Functionality
- Python Pandas - Timedelta
- Python Pandas - Sparse Data Structures
- Python Pandas - Sparse Data
- Python Pandas - Visualization
- Python Pandas - Visualization
- Python Pandas - Additional Concepts
- Python Pandas - Caveats & Gotchas
Pandas Series.str.count() Method
The Series.str.count() method in Pandas allows you to efficiently count the occurrences of a specified regex pattern within each string element of a Series or Index.
This method returns a Series or Index containing the number, representing how many times a specified regular expression is found in each string. This method is useful for analyzing and summarizing text data.
Syntax
Following is the syntax of the Pandas Series.str.count() method −
Series.str.count(pat, flags=0, **kwargs)
Parameters
The Series.str.count() method accepts the following parameters −
pat − A string representing the valid regular expression pattern to count.
flags − An integer value for regex flags from the re module. Default is 0 (no flags).
**kwargs − Additional arguments for compatibility with other string methods. Not used.
Return Value
The Series.str.count() method returns a Series or Index of the same type as the calling object, containing the integer counts of the pattern occurrences.
Example
In this example, we demonstrate the basic usage of the Series.str.count() method by counting the occurrences of the pattern 'a' in each string of a Series.
import pandas as pd import numpy as np # Create a Series of strings s = pd.Series(['Tutorialspoint', 'python', 'pandas', 'program', np.nan, 'example']) # Count occurrences of 'a' in each string result = s.str.count('a') print("Input Series:") print(s) print("\nSeries after calling str.count('a'):") print(result)
When we run the above code, it produces the following output −
Input Series: 0 Tutorialspoint 1 python 2 pandas 3 program 4 NaN 5 example dtype: object Series after calling str.count('a'): 0 1.0 1 0.0 2 2.0 3 1.0 4 NaN 5 1.0 dtype: float64
Example
This example demonstrates how to use the Series.str.count() method to count the occurrences of the pattern 'he|wo' in each string of a DataFrame column.
import pandas as pd # Create a DataFrame with a column of strings df = pd.DataFrame(['Python', 'pandas', 'tutorialspoint'], columns=['words']) # Count occurrences of 't' or 'o' in each string result = df.words.str.count("t|o") print("Input DataFrame:") print(df) print("\nDataFrame column after calling str.count('t|o'):") print(result)
Following is the output of the above code −
Input DataFrame: words 0 Python 1 pandas 2 tutorialspoint DataFrame column after calling str.count('t|o'): 0 2 1 0 2 5 Name: words, dtype: int64
Example
In this example, we use the Series.str.count() method to count the occurrences of the dollar sign ('$') in each string of a Series. Note that we need to escape the dollar sign using '\\$' to search for the literal character.
import pandas as pd # Create a Series of strings s = pd.Series(['$Python', 'pandas', 'p$yt$h$on', '$$C', 'C$++$', 'Python']) # Count occurrences of '$' in each string result = s.str.count('\\$') print("Input Series:") print(s) print("\nSeries after calling str.count('\\$'):") print(result)
Output of the above code is as follows −
Input Series: 0 $Python 1 pandas 2 p$yt$h$on 3 $$C 4 C$++$ 5 Python dtype: object Series after calling str.count('\$'): 0 1 1 0 2 3 3 2 4 2 5 0 dtype: int64
Example
In this example, we apply the Series.str.count() method to an Index of a Series object to count the occurrences of the pattern 'a' in each string.
import pandas as pd import numpy as np # Create a Series of strings s1 = pd.Series([1, 2, 3, 4], index=['Pandas', 'Python', 'Tutorialspoint', 'count']) # Count occurrences of 'a' in each string result = s1.index.str.count('a') print("Input Series:") print(s1) print("\nResult after calling str.count('a'):") print(result)
Output of the above code is as follows −
Input Series: Pandas 1 Python 2 Tutorialspoint 3 count 4 dtype: int64 Result after calling str.count('a'): Index([2, 0, 1, 0], dtype='int64')