我需要從列中的字串中提取所有匹配項并填充第二列。匹配項將由逗號分隔。
df2 = pd.DataFrame([[1000, 'Jerry', 'string of text BR1001_BR1003_BR9009 more string','BR1003',''],
[1001, '', 'BR1010_BR1011 random text', 'BR1010',''],
['', '', 'test to discardBR3009', 'BR2002',''],
[1003, 'Perry','BR4009 pure gibberish','BR1001',''],
[1004, 'Perry2','','BR1001','']],
columns=['ID', 'Name', 'REGEX string', 'Member of','Status'])
表示要提取的代碼的模式。
BR_pat = re.compile(r'(BR[0-9]{4})', re.IGNORECASE)
希望在列中輸出
BR1001, BR1003, BR9009
BR1010,BR1011
BR3009
BR4009
我的嘗試:
df2['REGEX string'].str.extractall(BR_pat).unstack().fillna('').apply(lambda x: ", ".join(x))
輸出:
match
0 0 BR1001, BR1010, BR3009, BR4009
1 BR1003, BR1011, ,
2 BR9009, , ,
缺少額外的逗號和行。我做錯了什么?
uj5u.com熱心網友回復:
你需要使用
>>> df2['REGEX string'].str.findall(r'BR\d{4}').str.join(", ")
0 BR1001, BR1003, BR9009
1 BR1010, BR1011
2 BR3009
3 BR4009
4
Name: REGEX string, dtype: object
使用Series.str.findall,您可以提取字串值中所有出現的模式,它會回傳“字串串列的系列/索引”。要將它們連接成單個字串,請Series.str.join()使用 。
uj5u.com熱心網友回復:
你也可以
- 添加
axis=1以apply使用列而不是行。 - 添加
filter(None,x)以過濾掉空字串。
結果是
df['REGEX string'].str.extractall(BR_pat).unstack().fillna('').apply(lambda x : ",".join(filter(None,x)), axis=1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/437257.html
