[英]How to check if Pandas column has value from list of string?
I have a dataframe and a list我有一个 dataframe 和一个列表
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']
I want to create a new column flag
such that if Names
column contain keyword from kw
, flag will be 1 else 0.我想创建一个新的列flag
,如果Names
列包含来自kw
的关键字,则标志将为 1,否则为 0。
Expected Output:预期 Output:
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:我可以使用以下代码获得 output:
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
Is there an alternate way to avoid for loop and making it more efficient?是否有另一种方法可以避免 for 循环并使其更有效?
Use apply
and lambda
like: 使用apply
和lambda
例如:
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
您可以使用熊猫的isin函数
df['Names'].isin(kw)
Hi is it possible to return the value from list?嗨,可以从列表中返回值吗?
IDs Names Flag 0 1234 APPLE ABCD ONE APPLE 1 5346 APPLE ABCD APPLE 2 1234 NO STRAWBERRY YES STRAWBERRY 3 8793 ORANGE AVAILABLE ORANGE 4 8793 TEA AVAILABLE ID 名称 标志 0 1234 APPLE ABCD ONE APPLE 1 5346 APPLE ABCD APPLE 2 1234 NO STRAWBERRY YES STRAWBERRY 3 8793 ORANGE AVAILABLE ORANGE 4 8793 TEA AVAILABLE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.