社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

python-检查列是否包含列表中的值,返回值

Justin • 5 年前 • 1479 次点击  

我有测向仪:

d = {'id': [1,2,3,4,5,6,7,8,9,10],
      'text': ['bill did this', 'jim did something', 'phil', 'bill did nothing',
               'carl was here', 'this is random', 'other name',
               'other bill', 'bill and carl', 'last one']}
df = pd.DataFrame(data=d)

我想检查列是否包含列表中的值,其中列表是:

list = ['bill','carl']

我想还这样的东西

id  text                    contains
1   bill did this           bill
2   jim did something       
3   phil                
4   bill did nothing        bill
5   carl was here           carl
6   this is random
7   other name
8   other bill              bill
9   bill and carl           bill
9   bill and carl           carl
10  last one

尽管在同一行中处理两个或多个名称的方法是开放的,可以更改的。 有什么建议吗?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/40000
 
1479 次点击  
文章 [ 1 ]  |  最新文章 5 年前
BernardL
Reply   •   1 楼
BernardL    6 年前

可以创建lambda函数来检查列表中的每个项:

d = {'id': [1,2,3,4,5,6,7,8,9,10],
      'text': ['bill did this', 'jim did something', 'phil', 'bill did nothing',
               'carl was here', 'this is random', 'other name',
               'other bill', 'bill and carl', 'last one']}
df = pd.DataFrame(data=d)

l = ['bill','carl']

df['contains'] = df['text'].apply(lambda x: ','.join([i for i in l if i in x]))

如果需要列表,可以删除join,否则它将只连接由逗号分隔的值。

产量

>>df['contains']

0         bill
1             
2             
3         bill
4         carl
5             
6             
7         bill
8    bill,carl
9             
Name: contains, dtype: object