Python Pandas TypeError:第一个参数必须是字符串或编译模式

2024-09-28 15:11:29 发布

您现在位置:Python中文网/ 问答频道 /正文

很抱歉,这个问题太简单了,但我做不到

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

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. 

Tags: 数据namematch错误np语句wherefirst
1条回答
网友
1楼 · 发布于 2024-09-28 15:11:29

如果您试图同时查找两个regex模式,就像在字符串中同时搜索?tourist。您可以使用|运算符。所以把pattern改成

pattern = "tourist|\?"

这将检查字符串中是否有问号“tourist”

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

相关问题 更多 >