Python:使用通配符在Pandas DataFrame列中查找字符串并保留行
保留Pandas DataFrame中包含任意形式"AWAIT"的行
嘿,我来帮你搞定这个问题!首先,要匹配Text列中任意形式的AWAIT(包括大小写变体、时态变体比如awaiting/awaited等),我们可以用Pandas的str.contains配合正则表达式来实现,同时避开常见的坑。
示例场景
假设你的原始DataFrame是这样的:
| ID | Text |
|---|---|
| 1 | We need to await your reply |
| 2 | AWAITING confirmation |
| 3 | This is a normal message |
| 4 | await further instructions |
| 5 | Awaiting your response |
| 6 | The task was awaited yesterday |
你期望保留所有Text列包含await相关形式的行(也就是ID1、2、4、5、6的行)。
正确实现代码
import pandas as pd # 构造示例DataFrame df = pd.DataFrame({ 'ID': [1, 2, 3, 4, 5, 6], 'Text': [ 'We need to await your reply', 'AWAITING confirmation', 'This is a normal message', 'await further instructions', 'Awaiting your response', 'The task was awaited yesterday' ] }) # 筛选包含任意形式await的行 # \b 确保匹配独立单词(避免匹配类似"unawaitable"这类词,不需要的话可以去掉) # await\w* 匹配await开头的所有变体(await、awaiting、awaited等) # case=False 忽略大小写 # na=False 处理Text列的空值,避免筛选时出现NaN导致错误 filtered_df = df[df['Text'].str.contains(r'\bawait\w*\b', case=False, na=False)] print(filtered_df)
常见错误及解决办法
- 错误1:只匹配到完全大写的"AWAIT",漏掉其他大小写形式
解决:加上case=False参数,让匹配忽略大小写。 - 错误2:匹配到包含"await"的长单词(比如"unawaitable")
解决:在正则里加上单词边界\b,确保只匹配独立的await相关单词。 - 错误3:遇到NaN值时报错或筛选结果异常
解决:加上na=False参数,把空值视为不匹配,避免干扰筛选。 - 错误4:无法匹配
awaiting/awaited这类时态变体
解决:用await\w*代替单纯的await,匹配所有以await开头的单词。
内容的提问来源于stack exchange,提问作者PineNuts0




