Movatterモバイル変換


[0]ホーム

URL:


Python Pandas Tutorial

Pandas Series.str.extract() Method



TheSeries.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 PandasSeries.str.extract() method −

Series.str.extract(pat, flags=0, expand=True)

Parameters

TheSeries.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 there module, such asre.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

TheSeries.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. Ifexpand=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 theSeries.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 pdimport numpy as np# Create a Series of stringss = pd.Series(['Python1', 'Tutorialspoint2', 'caT3', np.nan])# Extract letter followed by a digitresult = 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           Python11    Tutorialspoint22              caT33               NaNdtype: objectDataFrame after calling str.extract():  letter digit0      n     11      t     22      T     33    NaN   NaN

Example 2

In this example, we demonstrate how theSeries.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 stringss = pd.Series(['Order123', 'Invoice456', 'Receipt789'])# Extract 'Order', 'Invoice', or 'Receipt' followed by digitsresult = 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      Order1231    Invoice4562    Receipt789dtype: objectDataFrame after calling str.extract():      type number0    Order    1231  Invoice    4562  Receipt    789

Example 3

In this example, we demonstrate how theSeries.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 addressess = pd.Series(['user1@example.com', 'info@tutorialspoint.com', 'contact@website.org'])# Extract usernames from email addressesresult = 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.com1    info@tutorialspoint.com2        contact@website.orgdtype: objectDataFrame after calling str.extract():  username0    user11     info2  contact
python_pandas_working_with_text_data.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp