gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 08:10:43 25 4
gpt4 key购买 nike

我有一个 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

关于python - 如何使用正则表达式创建特定的虚拟变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70817448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com