Python Pandas Series.str.extract()
Series.str可以用来访问作为字符串的系列值,并对其应用几种方法。Pandas Series.str.extract()函数用于提取正则表达式pat中的捕获组作为DataFrame中的列。对于系列中的每个主题字符串,从正则表达式pat的第一个匹配中提取组。
语法:
Series.str.extract(pat, flags=0, expand=True)
参数:
pat : 带有捕获组的正则表达式模式。
flags : int, default 0 (no flags)
expand : 如果为真,则返回每个捕获组有一列的DataFrame。
返回:数据框架或系列或指数
示例#1:使用Series.str.extract()函数从给定系列对象的基础数据中的字符串中提取组。
# 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.extract()函数,从给定的系列对象中的字符串中提取组。
# extract groups having a vowel followed by
# any character
result = sr.str.extract(pat = '([aeiou].)')
# print the result
print(result)
输出 :
正如我们在输出中看到的,Series.str.extract()函数已经返回了一个包含提取组的列的数据框架。
示例#2 :使用Series.str.extract()函数从给定系列对象的基础数据中的字符串中提取组。
# 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.extract()函数,从给定的系列对象中的字符串中提取组。
# extract groups having any capital letter
# followed by 'i' and any other character
result = sr.str.extract(pat = '([A-Z]i.)')
# print the result
print(result)
输出 :
正如我们在输出中看到的,Series.str.extract()函数已经返回了一个包含提取组的列的数据框架。