[英]Extract words based on regex
我試圖提取出現在單詞 SUITE、suite、ste、Ste 之后的任何內容。 或熊貓數據框列中的字符 # 。 例子如下
4230 Harding Pike Ste 435
4230 Harding Pike Suite 435
4230 Harding Pike SUITE A
4230 Harding Pike Ste. 101
4230 Harding Pike SUITE B-200
4230 Harding Pike #900
4230 Harding Pike STE 503
4230 Harding Pike SUITE 300
4230 Harding Pike Ste 700
4230 Harding Pike SUITE #2
結果:
SuiteNos
435
435
A
101
B-200
900
503
300
700
2
我嘗試使用以下正則表達式,但它沒有按預期工作 -
df_merged['address'].str.extract(r'\**\**suite.*\**\**')
df_merged['address'] = re.findall('@([suite]+)', df_merged['address'])
使用不區分大小寫的匹配,您可以使用帶有交替的捕獲組:
(?i)(?:#|Suite|ste\.?)\s*([^\s#].*)
模式匹配:
(?:
非捕獲組
Suite
匹配字面意思|
或者ste\\.?
將 ste 與可選點匹配|
或者#
逐字匹配)
關閉非捕獲組\\s*
匹配可選的空白字符([^\\s#].*)
捕獲組 1,從匹配不帶 # 的非空白字符開始,以及該行的其余部分strings = [
"4230 Harding Pike Ste 435",
"4230 Harding Pike Suite 435",
"4230 Harding Pike SUITE A",
"4230 Harding Pike Ste. 101",
"4230 Harding Pike SUITE B-200",
"4230 Harding Pike #900",
"4230 Harding Pike STE 503",
"4230 Harding Pike SUITE 300",
"4230 Harding Pike Ste 700",
"4230 Harding Pike SUITE #2"
]
pattern = r"(?i)(?:#|Suite|ste\.?)\s*([^\s#].*)"
df_merged = pd.DataFrame(strings, columns = ['address'])
df_merged['SuiteNos'] = df_merged['address'].str.extract(pattern)
print(df_merged)
輸出
0 435
1 435
2 A
3 101
4 B-200
5 900
6 503
7 300
8 700
9 2
使用您顯示的示例,請嘗試以下正則表達式。
[Ss](?:[uU][iI])?[tT][eE](?:[.])?\s+#?(\S+)
在Pandas 中運行以下代碼:
df['value'].str.extract(r'[Ss](?:[uU][iI])?[tT][eE](?:[.])?\s+#?(\S+)')
Pandas 中的上述代碼和 OP 提供的示例的輸出如下:
0 435
1 435
2 A
3 101
4 B-200
5 NaN
6 503
7 300
8 700
9 2
Name: value, dtype: object
說明:為以上添加詳細說明。
[Ss] ##Matching small OR capital S here.
(?:[uU][iI])? ##In a non-capturing group matching u/U i/I and keep this optional.
[tT][eE] ##Matching t or T followed by e or E here.
(?:[.])? ##In a non-capturing group matching . and keeping it optional.
\s+#? ##Matching 1 or more occurrences of space here followed by # and keeping it optional match here.
(\S+) ##Creating 1st and only capturing group to catch everything non-space here.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.