str.包含多个值和 if-condition 错误::异常没有帮助,因为它没有提到正确的替代方案



另请注意:这篇文章没有回答我的问题: 序列的真值是不明确的。使用 a.empty、a.bool((、a.item((、a.any(( 或 a.all((

我通过以下方式使用 str.contains((:

df1['company'] = ""
search = ['Inc.','Company','Ltd','Co.']
if(df1['fu'].str.contains('|'.join(search), na=False)):
df1["company"] = "Yes"
else:
df1['company'] = "No"

虽然df1['fu'].str.contains('|'.join(searchfor), na=False)独立工作(即它打印真/假值(,但上面编写的代码会抛出值错误

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

令人困惑的是,df1['fu'].str.contains('|'.join(searchfor), na=False)确实返回布尔值。

注意:我不想使用 .all(( 或 .any((,因为我想要一个元素明智的 Truth/False 而不是整个集合。

df1['fu'].str.contains('|'.join(search), na=False)返回一个不支持if语句的Series,因为创建Series总是返回一个Series对象,无论是否为空。

回答您的问题;

# fill data-frame with True and False
df['company'] = df1['fu'].str.contains('|'.join(searchfor), na=False)
# replace True/False with 'yes'/'no'
# Note: True == 1 and False == 0
df['company'] = df['company'].apply(lambda x: ('no', 'yes')[x])
# as a one-liner 
df['company'] = ( df1['fu'].str.contains('|'.join(searchfor), na=False)
.apply(lambda x: ('no', 'yes')[x]) )

相关内容

最新更新