如何使用正则表达式提取多个字符串?

2024-06-16 11:48:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我在df中有一列包含以下值:

>>> import pandas as pd
>>> df = pd.DataFrame({'Sentence':['his is the results of my experiments KEY_abc_def KEY_mno_pqr KEY_blt_chm', 'I have researched the product KEY_abc_def, and KEY_blt_chm as requested', 'He got the idea from your message KEY_mno_pqr']})
>>> df
                                                Sentence
0       This is the results of my experiments KEY_abc_def KEY_mno_pqr KEY_blt_chm
1  I have researched the product KEY_abc_def, and KEY_blt_chm as requested
2            He got the idea from your message KEY_mno_pqr

我想使用regex将键提取到一个新列中,而不使用实际的“KEY”。对于那些有多个键的句子,它们应该用逗号连接。输出应如下所示:

>>> df
                                                Sentence                               KEY
0      This is the results of my experiments KEY_abc_def KEY_mno_pqr KEY_blt_chm    abc_def, mno_pqr, blt_chm
1  I have researched the product KEY_abc_def, and KEY_blt_chm as requested          abc_def, blt_chm     
2           He got the idea from your message KEY_mno_pqr                           mno_pqr  

我尝试使用此代码,但它不起作用。如有任何建议,将不胜感激

我目前只使用第一个键的代码,而忽略了其余的。我是新加入regex的,所以任何建议都将不胜感激

df['KEY']= df.sentence.str.extract("KEY_(\w+)", expand=True)

Tags: ofthekeydfismydefas
1条回答
网友
1楼 · 发布于 2024-06-16 11:48:17

使用

df['KEY']= df.sentence.str.findall("KEY_(\w+)").str.join(",")

Series.str.findall查找捕获的子字符串的所有匹配项,并str.join(",")将结果合并为逗号分隔的字符串值

熊猫测试:

>>> df['KEY']= df['Sentence'].str.findall("KEY_(\w+)").str.join(",")
>>> df
                                                                   Sentence                      KEY
0  his is the results of my experiments KEY_abc_def KEY_mno_pqr KEY_blt_chm  abc_def,mno_pqr,blt_chm
1   I have researched the product KEY_abc_def, and KEY_blt_chm as requested          abc_def,blt_chm
2                             He got the idea from your message KEY_mno_pqr                  mno_pqr

(请注意,如果您不知道:我使用了pd.set_option('display.max_colwidth', None)来显示列中的所有数据,请参见How to display full (non-truncated) dataframe information in html when converting from pandas dataframe to html?

相关问题 更多 >