python - 如何使用正则表达式创建特定的虚拟变量?

我有一个 Pandas 数据框:

col1
johns id is 81245678316
eric bought 82241624316 yesterday
mine is87721624316
frank is a genius
i accepted new 82891224316again

我想根据 col1 创建带有虚拟变量 (0,1) 的新列。如果有 11 个数字以 8 开头并连续出现,则必须为 1,否则为 0。

所以我写了这段代码:

df["is_number"] = df.col1.str.contains(r"\b8\d{10}").map({True: 1, False: 0})

但是输出是:

col1                                         is_number
johns id is 81245678316                        1
eric bought 82241624316 yesterday              1
mine is87721624316                             0
frank is a genius                              0
i accepted new 82891224316again                0      

如您所见,第三行和第五行在“is_number”中有 0,但我希望它们有 1,即使某些地方的单词和数字之间缺少空格。怎么做?我要:

col1                                         is_number
johns id is 81245678316                        1
eric bought 82241624316 yesterday              1
mine is87721624316                             1
frank is a genius                              0
i accepted new 82891224316again                1      

最佳答案

您可以使用数字边界,因为输入中的数字可以“粘合”到字母(这是单词边界,因此字母和 8 之间没有单词边界):

df["is_number"] = df['col1'].str.contains(r"(?<!\d)8\d{10}(?!\d)").map({True: 1, False: 0})

输出:

>>> df
                                col1  is_number
0            johns id is 81245678316          1
1  eric bought 82241624316 yesterday          1
2                 mine is87721624316          1
3                  frank is a genius          0
4    i accepted new 82891224316again          1

参见 regex demo 。

https://stackoverflow.com/questions/70817448/

相关文章:

python - 在不保留旧父类的情况下用另一个类替换父类

postgresql - 了解全文搜索查询中子句顺序的影响

javascript - Firebase AppCheck 网络应用程序无法在生产模式下运行

mysql - Prisma - 唯一约束失败,而架构中没有唯一字段

vue.js - 从 axios 中的 response.headers 访问 Set-Cookie

css - 使用 CSS 模块时从父项覆盖样式的 'correct' 方法是什么?

SQL 查询 - 当我们在 where 子句中使用主键时更新/删除语句的性能

javascript - 根据 HTML 规范对模块脚本执行严格的 MIME 类型检查

php - 是什么导致我的 Laravel 8 应用程序出现此查询生成器错误?

firebase - 为什么 Firebase 动态链接总是空的?