当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Python Pandas Series.str.extractall()用法及代码示例

Series.str可用于以字符串形式访问系列的值并对其应用几种方法。 Pandas Series.str.extractall()函数用于提取正则表达式中的捕获组作为DataFrame中的列。对于系列中的每个主题字符串,从正则表达式pat的所有匹配项中提取组。当系列中的每个主题字符串完全匹配一个匹配项时,extractall(pat).xs(0,level ='match')与extract(pat)相同。

用法: Series.str.extractall(pat, flags=0)

参数:
pat:具有捕获组的正则表达式模式。
flags:一个re模块标志,例如re.IGNORECASE。


返回: DataFrame

范例1:采用Series.str.extractall()函数从给定系列对象的基础数据中的字符串中提取所有组。

# importing pandas as pd 
import pandas as pd 
  
# importing re for regular expressions 
import re 
  
# Creating the Series 
sr = pd.Series(['New_York', 'Lisbon', 'Tokyo', 'Paris', 'Munich']) 
  
# Creating the index 
idx = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] 
  
# set the index 
sr.index = idx 
  
# Print the series 
print(sr)

输出:

现在我们将使用Series.str.extractall()函数从给定系列对象中的字符串中提取所有组。

# extract all groups having a vowel followed by 
# any character 
result = sr.str.extractall(pat = '([aeiou].)') 
  
# print the result 
print(result)

输出:

正如我们在输出中看到的,Series.str.extractall()函数已返回一个包含所有已提取组的列的 DataFrame 。

范例2:采用Series.str.extractall()函数从给定系列对象的基础数据中的字符串中提取所有组。

# importing pandas as pd 
import pandas as pd 
  
# importing re for regular expressions 
import re 
  
# Creating the Series 
sr = pd.Series(['Mike', 'Alessa', 'Nick', 'Kim', 'Britney']) 
  
# Creating the index 
idx = ['Name 1', 'Name 2', 'Name 3', 'Name 4', 'Name 5'] 
  
# set the index 
sr.index = idx 
  
# Print the series 
print(sr)

输出:


现在我们将使用Series.str.extractall()函数从给定系列对象中的字符串中提取所有组。

# extract all groups having any capital letter 
# followed by 'i' and any other character 
result = sr.str.extractall(pat = '([A-Z]i.)') 
  
# print the result 
print(result)

输出:

正如我们在输出中看到的,Series.str.extractall()函数已返回一个包含所有已提取组的列的 DataFrame 。



相关用法


注:本文由纯净天空筛选整理自Shubham__Ranjan大神的英文原创作品 Python | Pandas Series.str.extractall()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。