
- 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.extract() Method
The Series.str.extract() method in Pandas allows you to extract sub-strings that match a specified regular expression pattern from each string element in a Series or columns in a DataFrame. This method is particularly useful for extracting specific parts of strings based on regular expression patterns into separate columns in a DataFrame.
By using the regular expression pattern, you can easily control which parts of the strings are extracted. This method extracts groups from the first match of the regular expression pattern. Then the extracted groups can be returned as columns in a DataFrame, making it easy to work with complex text data.
Syntax
Following is the syntax of the Pandas Series.str.extract() method −
Series.str.extract(pat, flags=0, expand=True)
Parameters
The Series.str.extract() method accepts the following parameters −
pat − A string representing the regular expression pattern with capturing groups.
flags − An integer, default is 0 (no flags). Flags from the re module, such as re.IGNORECASE, can be used to modify regular expression matching.
expand − A boolean, default is True. If True, returns a DataFrame with one column per capture group. If False, returns a Series/Index if there is one capture group, or a DataFrame if there are multiple capture groups.
Return Value
The Series.str.extract() method returns a DataFrame, Series, or Index. The result will have one row for each subject string and one column for each group. Capture group names in the regular expression pattern will be used for column names; otherwise, capture group numbers will be used. The dtype of each result column is always object, even when no match is found. If expand=False and the pattern has only one capture group, then a Series or Index is returned.
Example 1
In this example, we demonstrate the usage of the Series.str.extract() method by extracting specific parts of the strings in a Series based on a regular expression pattern.
Here, we have used a regular expression pattern with named capturing groups to extract a letter followed by a digit from each string in the Series.
import pandas as pd import numpy as np # Create a Series of strings s = pd.Series(['Python1', 'Tutorialspoint2', 'caT3', np.nan]) # Extract letter followed by a digit result = s.str.extract(r'(?P<letter>[a-zA-Z])(?P<digit>\d)') print("Input Series:") print(s) print("\nDataFrame after calling str.extract():") print(result)
When we run the above code, it produces the following output −
Input Series: 0 Python1 1 Tutorialspoint2 2 caT3 3 NaN dtype: object DataFrame after calling str.extract(): letter digit 0 n 1 1 t 2 2 T 3 3 NaN NaN
Example 2
In this example, we demonstrate how the Series.str.extract() method can be used to extract specific parts of strings in a Series based on a regular expression pattern with multiple capturing groups.
import pandas as pd # Create a Series of strings s = pd.Series(['Order123', 'Invoice456', 'Receipt789']) # Extract 'Order', 'Invoice', or 'Receipt' followed by digits result = s.str.extract(r'(?P<type>[A-Za-z]+)(?P<number>\d+)') print("Input Series:") print(s) print("\nDataFrame after calling str.extract():") print(result)
Following is the output of the above code −
Input Series: 0 Order123 1 Invoice456 2 Receipt789 dtype: object DataFrame after calling str.extract(): type number 0 Order 123 1 Invoice 456 2 Receipt 789
Example 3
In this example, we demonstrate how the Series.str.extract() method can be used to extract email usernames from a Series of email addresses.
import pandas as pd # Create a Series of email addresses s = pd.Series(['user1@example.com', 'info@tutorialspoint.com', 'contact@website.org']) # Extract usernames from email addresses result = s.str.extract(r'(?P<username>^[^@]+)') print("Input Series:") print(s) print("\nDataFrame after calling str.extract()):") print(result)
Following is the output of the above code −
Input Series: 0 user1@example.com 1 info@tutorialspoint.com 2 contact@website.org dtype: object DataFrame after calling str.extract(): username 0 user1 1 info 2 contact