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
python_pandas_working_with_text_data.htm
Advertisements