"in" 和 str.contains() 做同样的事情吗?
Does "in" do the same thing as str.contains()?
我是 Python 的新手,但对这段代码的工作原理感到非常困惑:
我不明白的正确代码:
我不明白如何在函数中,您可以在域中写入“.org”来捕获 referrer_domain 是否是一个组织。我以为您必须通过 .[=28 进行过滤=]() 能够查看域是否包含 .org 或 .com。
我最初编码:
dot_org = data[data['referrer_domain'].str.contains('.org')
dot_com = data[data['referrer_domain'].str.contains('.com')
def domain_type(type):
if type in dot_org['referrer_domain']:
return 'organization'
elif type in dot_com['referrer_domain']:
return 'company'
else:
return 'other'
data['new_column'] = data['referrer_domain'].apply(domain_type)
但这最终将我创建的新列中的所有行都标记为“其他”。
有谁能解释为什么图片中的代码有效,而上面的代码却不行?
首先,你不应该使用 type
作为变量名,因为它是一个保留字。
除此之外,没有 str.contains
方法,至少在普通 Python 中没有。检查一个字符串是否包含另一个字符串的官方方法是使用 the in
operator.
我是 Python 的新手,但对这段代码的工作原理感到非常困惑:
我不明白的正确代码:
我不明白如何在函数中,您可以在域中写入“.org”来捕获 referrer_domain 是否是一个组织。我以为您必须通过 .[=28 进行过滤=]() 能够查看域是否包含 .org 或 .com。
我最初编码:
dot_org = data[data['referrer_domain'].str.contains('.org')
dot_com = data[data['referrer_domain'].str.contains('.com')
def domain_type(type):
if type in dot_org['referrer_domain']:
return 'organization'
elif type in dot_com['referrer_domain']:
return 'company'
else:
return 'other'
data['new_column'] = data['referrer_domain'].apply(domain_type)
但这最终将我创建的新列中的所有行都标记为“其他”。
有谁能解释为什么图片中的代码有效,而上面的代码却不行?
首先,你不应该使用 type
作为变量名,因为它是一个保留字。
除此之外,没有 str.contains
方法,至少在普通 Python 中没有。检查一个字符串是否包含另一个字符串的官方方法是使用 the in
operator.