我在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)
使用
Series.str.findall
查找捕获的子字符串的所有匹配项,并str.join(",")
将结果合并为逗号分隔的字符串值熊猫测试:
(请注意,如果您不知道:我使用了
pd.set_option('display.max_colwidth', None)
来显示列中的所有数据,请参见How to display full (non-truncated) dataframe information in html when converting from pandas dataframe to html?)相关问题 更多 >
编程相关推荐