这里有点初学者问题;我目前有一个 pandas df,其中一列包含各种不同的字符串。我还有一些当前为空的列。以下前几行的示例;
Risk,Cost,Productivity,Security
"Unforeseen cost due to CCTV failures",,,
"Unexpected drop in Productivity",,,
我还创建了一组列表如下;
Cost = ['Cost']
Productivity = ['Productivity']
Security = ['Security','CCTV','Camera']
基本上我想做的是遍历每一列并检查同一行“风险”列中的字符串是否包含与列表中的字符串之一匹配的子字符串。理想的输出如下;
Risk,Cost,Productivity,Security
"Unforeseen cost due to security issues",TRUE,FALSE,TRUE
"Unexpected drop in Productivity",FALSE,TRUE,FALSE
到目前为止,我已经尝试了几种不同的方法,比如
any(Cost in Risk for Cost in Costs)
但是,我不确定是否有办法避免 any() 函数区分大小写,而且我不确定如何将其应用于整个列。我确实尝试过
df['Cost'] = any(Cost in df['Risk'] for Cost in Costs)
但是返回的列中全是“FALSE”。任何朝着正确方向的插入将不胜感激!谢谢
最佳答案
我们可以创建一个对应于列表Cost
、Security
和Productivity
的正则表达式模式,然后使用str.contains
测试列 Risk
for c in ('Cost', 'Productivity', 'Security'):
df[c] = df['Risk'].str.contains(fr"(?i)\b(?:{'|'.join(locals()[c])})\b")
Risk Cost Productivity Security
0 Unforeseen cost due to CCTV failures True False True
1 Unexpected drop in Productivity False True False
https://stackoverflow.com/questions/67569316/
相关文章:
amazon-web-services - 为什么 X-Forwarded-Proto 在 Elas
kubernetes - 如何将 kubernetes 的一个 secret 值复制到同一 name
python-3.x - DistutilsError : Could not find suita
node.js - 如何使用 NestJS 为多个国家/地区编写调度程序 12 :00AM(will
haskell - 在 haskell 中给 `_` 一个类型签名
javascript - 如何在一组 span 元素之后替换纯文本内容或文本节点?