如何检查 Pandas 列是否具有字符串列表中的值? [英] How to check if Pandas column has value from list of string?

查看:95
本文介绍了如何检查 Pandas 列是否具有字符串列表中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框和一个列表

I have a dataframe and a list

df = pd.DataFrame({'IDs':[1234,5346,1234,8793,8793],
                    'Names':['APPLE ABCD ONE','APPLE ABCD','NO STRAWBERRY YES','ORANGE AVAILABLE','TEA AVAILABLE']})

kw = ['APPLE ABCD', 'ORANGE', 'LEMONS', 'STRAWBERRY', 'BLUEBERRY', 'TEA COFFEE']

我想创建一个新列 flag,这样如果 Names 列包含来自 kw 的关键字,flag 将为 1,否则为 0.

I want to create a new column flag such that if Names column contain keyword from kw, flag will be 1 else 0.

预期输出:

    IDs     Names               Flag
0   1234    APPLE ABCD ONE      1
1   5346    APPLE ABCD          1
2   1234    NO STRAWBERRY YES   1
3   8793    ORANGE AVAILABLE    1
4   8793    TEA AVAILABLE       0

我可以使用以下代码获得输出:

I am able to get the output using below code:

ind=[]
for idx, value in df.iterrows():
    x = 0
    for u in kw:
        if u in value['Names']:
            ind.append(True)
            x = 1
            break
    if x == 0:
        ind.append(False)

df['flag'] = ind

是否有其他方法可以避免 for 循环并使其更高效?

Is there an alternate way to avoid for loop and making it more efficient?

推荐答案

使用 applylambda 如:

df['Names'].apply(lambda x: any([k in x for k in kw]))

0     True
1     True
2     True
3     True
4    False
Name: Names, dtype: bool

这篇关于如何检查 Pandas 列是否具有字符串列表中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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