【问题标题】:Python - Remove words from variablePython - 从变量中删除单词
【发布时间】:2022-08-18 20:32:54
【问题描述】:

我正在尝试从数据框中的变量中删除任何出现的 \'Doctor\'、\'Honorable\' 和 \'Professor\'。这是数据框的示例:

Name
professor Rick Smith
Mark M. Tarleton
Doctor Charles M. Alexander
Professor doctor Todd Mckenzie
Carl L. Darla
Honorable Billy Darlington

观察可以有多个、一个或没有:\'Doctor\'、\'Honorable\' 或 \'Professor\'。此外,这些术语可以是大写或小写。

任何帮助将非常感激!

    标签: python string dataframe replace


    【解决方案1】:

    使用带有str.replace 的正则表达式:

    regex = '(?:Doctor|Honorable|Professor)\s*'
    
    df['Name'] = df['Name'].str.replace(regex, '', regex=True, case=False)
    

    输出:

                       Name
    0            Rick Smith
    1      Mark M. Tarleton
    2  Charles M. Alexander
    3         Todd Mckenzie
    4         Carl L. Darla
    5      Billy Darlington
    

    regex demo

    【讨论】:

    • 这真的很好用!你能解释一下每一行代码在做什么吗?
    • 这定义了一个 regex 以匹配三个单词中的任何一个,然后使用可选空格并将它们替换为空字符串。我添加了一个链接来解释这个正则表达式是如何工作的。
    猜你喜欢
    • 2015-07-12
    • 1970-01-01
    • 2019-09-05
    • 2021-08-20
    • 1970-01-01
    • 2022-07-03
    • 2017-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多