【问题标题】:Python: .str.replace(r'.*=','') not sure what it is being replaced with empty ""Python:.str.replace(r'.*=','') 不确定它被替换为空“”
【发布时间】:2019-12-26 21:12:06
【问题描述】:

我在学习 Python 时遇到了以下关于 pandas 的语句:

humans['Education'] = (humans[
    'Years of post-secondary education (e.g. BA=4; Ph.D.=10)'] .str.replace(r'.*=','').astype(int))

我知道它会创建额外的列,但不确定 replace(r'.*=','') 功能。

【问题讨论】:

  • r'.*=' 是正则表达式 (RegEx),.匹配任何字符,而星号表示匹配一个或多个前面的标记(点)。最后一个标记 = 匹配一个 '=' 字符。匹配此模式的任何内容都将替换为空字符串

标签: python string replace sklearn-pandas


【解决方案1】:

这是一个正则表达式(请参阅https://en.wikipedia.org/wiki/Regular_expression),因此该函数将匹配表达式的内容替换为任何内容(请参阅作为第二个参数给出的'')。

要查看正则表达式的作用,可以使用https://regex101.com/。在您的情况下,它会删除 = 符号(包括等号)之前的所有文本。注意引用字符串前面的r在这里解释:What does the "r" in pythons re.compile(r' pattern flags') mean?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-17
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多