【问题标题】:Python Pandas TypeError: first argument must be string or compiled patternPython Pandas TypeError:第一个参数必须是字符串或编译模式
【发布时间】:2018-02-07 03:37:01
【问题描述】:

对于这个超级简单的问题,我很抱歉,但我做不到

我正在清理数据并想添加一个标志,如果名称(分为两列名字和姓氏)是错误的。我建立了多种模式,但现在我使用的是单独的语句,我可以将所有这些语句合并为一个吗?

pattern = "\?"
match = incremental['First_Name'].str.contains(pattern) | incremental['Last_Name'].str.contains(pattern)
incremental['Name_Flag'] = np.where(match, 'Y', '')

pattern = "tourist"
    match = incremental['First_Name'].str.contains(pattern) | incremental['Last_Name'].str.contains(pattern)
    incremental['Name_Flag'] = np.where(match, 'Y', '')

这不起作用,因为第二个语句覆盖了第一个语句。

pattern = ("tourist","/?")
        match = incremental['First_Name'].str.contains(pattern) | incremental['Last_Name'].str.contains(pattern)
        incremental['Name_Flag'] = np.where(match, 'Y', '')

我收到第二个版本的错误(不足为奇)

TypeError: first argument must be string or compiled pattern. 

【问题讨论】:

  • 我有点困惑。您可以添加一些示例输入和预期输出吗?您是否希望结合正则表达式模式?想要检查这两种模式?最终目标问题是什么?

标签: python pandas pattern-matching syntax-error


【解决方案1】:

如果您正在尝试查找两种正则表达式模式 - 就像在字符串中搜索 ?tourist 一样。您可以使用| 运算符。所以把pattern改成

pattern = "tourist|\?"

这将检查问号 OR 如果 'tourist` 在字符串中

如果您想检查正则表达式,pythex 是一个非常好的地方。我给你做了一个测试。

【讨论】:

  • Ph - wow - 谢谢“pythex”太棒了,希望谷歌能在几个小时前给我...
  • @jeangelj 很高兴。玩得开心编码
  • “?”有问题,它用 Y 标记所有内容
  • 根据正则表达式模式测试 pythex 中的字符串,看看它是否匹配。如果不匹配,则代码中的其他地方会导致“Y”
猜你喜欢
  • 2018-09-14
  • 1970-01-01
  • 1970-01-01
  • 2021-03-30
  • 2020-05-05
  • 2019-11-04
  • 2021-12-17
  • 2020-09-11
  • 1970-01-01
相关资源
最近更新 更多