python - 使用 Regex Python 删除数据框中字符串中的前 2 个单词和后 2 个单词
问题描述
我在 df 中有一列包含以下字符串:
>>> import pandas as pd
>>> df = pd.DataFrame({'Sentence':['The cat is jumping off the bridge', 'The dog jumped over the brown fox, the bus is coming now', 'The bus is coming']})
>>> df
Sentence
0 The cat is jumping off the bridge
1 The dog jumped over the brown fox, the bus is coming now
2 The bus is coming
我想使用正则表达式删除所有字符串的前 2 个单词和最后 2 个单词。一行可以包含多个字符串(row 1)
。如果字符串少于 4 个单词,则不应为该字符串返回任何内容(row 2)
。输出应如下所示:
>>> df
Sentence String
0 The cat is jumping off the bridge is jumping off
1 The dog jumped over the brown fox, the bus is coming now jumped over the, is
2 The bus is coming
我尝试使用此代码只是为了查看它对前两个单词的工作原理,但它不起作用。任何建议将不胜感激。
df['String']= df.Sentence.str.join(line.split()[2:])
解决方案
您可以使用一次调用Series.str.replace
with
df['Sentence'].str.replace(r'(?<![^,])\s*\w+(?:\W+\w+)?\s*|\s*\w+(?:\W+\w+)?\s*(?![^,])', '')
请参阅 Pandas 演示:
>>> pattern = r'(?<![^,])\s*\w+(?:\W+\w+)?\s*|\s*\w+(?:\W+\w+)?\s*(?![^,])'
>>> df['Sentence'].str.replace(pattern, '')
0 is jumping off
1 jumped over the,is
2
正则表达式详细信息
(?<![^,])
- 逗号或字符串开头必须立即出现在当前位置的左侧\s*
- 0+ 个空格\w+
- 一个或多个单词字符(?:\W+\w+)?
- 一个或多个非单词字符的可选出现,后跟一个或多个单词字符\s*
- 0+ 个空格|
- 或者\s*
- 0+ 个空格\w+
- 一个单词(一个或多个单词字符)(?:\W+\w+)?
- 一个或多个非单词字符的可选出现,后跟一个或多个单词字符\s*
- 0+ 个空格(?![^,])
- 字符串结尾,或紧跟逗号的位置。
推荐阅读
- ios - 在 IOS 中用自定义 SFSafariViewController 替换 AppAuth
- laravel - 调用未定义的方法 Illuminate\Container\Container::getLocale() | 拉拉维尔 8
- grpc-web - gRPC-js + Angular ngx-grpc - Stream 在收到 4 条消息后停止接收消息
- r - 将宽数据帧重塑为长格式
- php - 比较数组值并选择特定的值
- linux - X11 窗口失去 Qt 窗口的活动状态
- keycloak - 我可以将“主题提示”传递给 Keycloak,例如 kc_idp_hint
- ruby-on-rails - 在 Elasticsearch 索引更新完成之前查询返回旧数据
- angular - 角度路由延迟加载不适用于书签路线
- azure - 使用 LogicApp 占用 40 分钟的并行性三重 Foreach 执行缓慢?