使用Apply检查pandas系列中的每一行是否包含列表中的字符串? [英] Check if each row in a pandas series contains a string from a list using apply?
本文介绍了使用Apply检查pandas系列中的每一行是否包含列表中的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试向DF添加一列,具体取决于其他列的值是否包含列表中的任何字符串.
I'm trying to add a column to the DF, depending on whether other column's value contains any of the strings in a list.
列表为:
services = [
"TELECOM",
"AYSA",
"PERSONAL"
]
到目前为止我已经尝试过:
And so far I've tried:
payments["category"] = "services" if payments["concept"].contains(service for service in services) else ""
还有这个:
payments["category"] = payments["concept"].apply(lambda x: "services" if x.contains(service) for service in services) else ""
在其他一些变化中...我看到了其他问题,但它们大多与相反的问题有关(检查列的值是否包含在列表中的字符串中)
Among some other variations... I've seen other questions but they're mostly related to the opposite problem (checking whether a column's value is contained by a string in a list)
我可以使用您的帮助!谢谢!
I could use your help! Thanks!!
推荐答案
您可以使用 np.where
和 str.contains
:
payments['category'] = np.where(payments['concept'].str.contains('|'.join(services)),
'services', '')
输出:
concept category
0 TELECOM services
1 AYSA services
2 PERSONAL services
3 other things
这篇关于使用Apply检查pandas系列中的每一行是否包含列表中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文