Pandas Series.str.extractall() 方法



Pandas 中的 Series.str.extractall() 方法用於從 Series 中正則表示式模式的所有匹配項中提取捕獲組。提取的組作為 DataFrame 中的列返回。

此方法對於提取 Series 中每個字串元素內模式的多個匹配項特別有用,並且可以用於文字資料分析和文字處理應用程式,尤其是在處理包含需要提取的多個模式的字串時。

語法

以下是 Pandas Series.str.extractall() 方法的語法:

Series.str.extractall(pat, flags=0)

引數

Series.str.extractall() 方法接受以下引數:

  • pat - 表示具有捕獲組的正則表示式模式的字串。

  • flags - 可選整數,預設為 0(無標誌)。可以使用來自 re 模組的標誌,例如 re.IGNORECASE。可以使用按位 OR 運算子組合多個標誌。

返回值

Series.str.extractall() 方法返回一個 DataFrame,其中每行對應一個匹配項,每列對應一個組。行具有多級索引,其中第一級來自主題 Series,最後一級命名為“match”以索引 Series 中每個專案中的匹配項。將使用正則表示式模式中的捕獲組名稱作為列名;否則,將使用捕獲組編號。

示例 1

此示例演示如何從 Series 中每個字串元素中提取所有模式匹配項。

import pandas as pd

# Create a Series of strings
s = pd.Series(['abc123def', '456ghi789', '000jkl'])

# Extract all digit groups from the strings
result = s.str.extractall(r'(\d+)')

print("Input Series:")
print(s)
print("\nExtracted Groups:")
print(result)

當我們執行以上程式碼時,它會產生以下輸出:

Input Series:
0    abc123def
1    456ghi789
2       000jkl
dtype: object

Extracted Groups:
         0
  match    
0 0    123
1 0    456
  1    789
2 0    000

示例 2

此示例演示如何從 Series 中每個字串元素中提取命名捕獲組。

import pandas as pd

# Create a Series of strings
s = pd.Series(['name: John, age: 30', 'name: Larry, age: 25', 'name: Mark, age: 35'])

# Extract name and age using named capture groups
pattern = r'name: (?P<name>\w+), age: (?P<age>\d+)'
result = s.str.extractall(pattern)

print("Input Series:")
print(s)
print("\nExtracted Groups with Named Capture Groups:")
print(result)

以下是以上程式碼的輸出:

Input Series:
0     name: John, age: 30
1    name: Larry, age: 25
2     name: Mark, age: 35
dtype: object

Extracted Groups with Named Capture Groups:
          name age
  match           
0 0       John  30
1 0      Larry  25
2 0       Mark  35

示例 3

此示例演示如何使用 re.IGNORECASE 標誌以不區分大小寫的方式提取匹配項。

import pandas as pd
import re

# Create a Series of strings
s = pd.Series(['Python', 'python', 'PYTHON', 'Pandas', 'pandas', 'PANDAS'])

# Extract all occurrences of 'python' or 'pandas' in a case-insensitive manner
pattern = r'(python|pandas)'
result = s.str.extractall(pattern, flags=re.IGNORECASE)

print("Input Series:")
print(s)
print("\nExtracted Groups with Case-Insensitive Matching:")
print(result)

以下是以上程式碼的輸出:

Input Series:
0    Python
1    python
2    PYTHON
3      Pandas
4      pandas
5      PANDAS
dtype: object

Extracted Groups with Case-Insensitive Matching:
        0
  match      
0 0  Python
1 0  python
2 0  PYTHON
3 0    Pandas
4 0    pandas
5 0    PANDAS
python_pandas_working_with_text_data.htm
廣告