如何根据Comments列是否包含Verizon创建布尔型True/False新列
实现Comments列包含Verizon的标记逻辑
直接用pandas内置的字符串向量化方法即可,不需要逐行循环处理,效率更高。
- 首先构造和示例一致的原始DataFrame:
import pandas as pd df = pd.DataFrame({ "Comments": [ "Yes - Verizon", "Verizon", "", "Does not contain ", "T-Mobile", "Standby, call for more", "Verizon Software" ] })
- 执行匹配逻辑,新增标记列:
df["Has Verizon?"] = df["Comments"].str.contains("Verizon", na=False)
运行后得到的结果和预期完全一致:
Comments Has Verizon? 0 Yes - Verizon True 1 Verizon True 2 False 3 Does not contain False 4 T-Mobile False 5 Standby, call for more False 6 Verizon Software True
说明
- 参数
na=False会对空字符串、缺失值等无有效文本的行直接返回False,避免出现空值干扰结果 - 默认匹配是区分大小写的,如果需要同时识别小写、全大写的同类写法(比如
verizon、VERIZON),可以给方法传入case=False参数,即:
df["Has Verizon?"] = df["Comments"].str.contains("Verizon", case=False, na=False)
内容的提问来源于stack exchange,提问作者Chris90
相关产品推荐
相关产品推荐

