如何确定一列是否包含 pandas 中的某些元素 [英] How to determine if a column contains certain elements in pandas

查看:62
本文介绍了如何确定一列是否包含 pandas 中的某些元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查列app是否包含myList的元素.

I want to check if the column app contains the element of myList.

import pandas as pd 
df=pd.DataFrame({'app':['a,b,c','e,f']})
myList=['b', 'f']
print(df)

Output:

     app
0  a,b,c
1    e,f

Expected:

     app  contains_b  contains_f
0  a,b,c          1           0
1    e,f          0           1

推荐答案

使用

Use str.get_dummies for all indicator columns and then filter them by reindex by list:

df = df.join(df['app'].str.get_dummies(',').reindex(columns=myList).add_prefix('contains_'))
print (df)
     app  contains_b  contains_f
0  a,b,c           1           0
1    e,f           0           1

或将循环与 str.contains 并将布尔型掩码转换为整数:

Or use loop with str.contains and casting boolean mask to integers:

for c in myList:
    df[f'contains_{c}'] = df['app'].str.contains(c).astype(int)
print (df)
     app  contains_b  contains_f
0  a,b,c           1           0
1    e,f           0           1

这篇关于如何确定一列是否包含 pandas 中的某些元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆