提取单词周围的单词并在数据帧列中插入结果

2024-06-16 14:16:39 发布

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

我有一个dataframe,df,有3列,如下所示:

company | year | text  
Apple   | 2016 |"The Company sells its products worldwide through its..."  

我想在df['text']中搜索“products”,并提取“products”之前和之后的3个单词,并将前面和后面的3个单词分别插入数据框中的两列,df['before']和{}。在

这是我目前所做的:

^{pr2}$

不过,我得到的信息是:

TypeError: expected string or buffer

我该怎么做?在


Tags: the数据textappledataframedf单词year
1条回答
网友
1楼 · 发布于 2024-06-16 14:16:39

使用^{}

pat = '(?P<before>(?:\w+\W+){,3})products\W+(?P<after>(?:\w+\W+){,3})'
new = df.text.str.extract(pat, expand=True)

new

               before                     after
0  Company sells its   worldwide through its...

可以使用新列创建新的数据帧

^{pr2}$

相关问题 更多 >