问题描述
我是 Python 新手,但对这段代码的工作方式感到非常困惑:
我不明白的正确代码:
我不明白在函数中如何,你可以在域中写“.org”来捕获referrer_domain是否是一个组织。我认为你必须通过.str.contains()过滤才能查看域是否包含 .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。