【发布时间】:2021-03-09 04:53:53
【问题描述】:
我在 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
我想使用正则表达式将 KEY 提取到没有实际“KEY_”的新列中。对于超过 1 个 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
我尝试使用此代码,但它不起作用。任何建议将不胜感激。
我目前只使用第一个 KEY 的代码,而忽略了其余部分。我是正则表达式的新手,所以任何建议都将受到高度赞赏。
df['KEY']= df.sentence.str.extract("KEY_(\w+)", expand=True)
【问题讨论】:
-
我敢打赌,无论你想做什么,ANTLR 都是一种更好的方法