Python Pandas Series.str.extractall()
Series.str可以用来将系列的值作为字符串访问,并对其应用几种方法。Pandas Series.str.extractall()函数用于提取正则表达式pat中的捕获组作为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()函数返回了一个包含所有提取组的列的数据框架。
示例#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()函数返回了一个包含所有提取组的列的数据框架。