[英]operation AND in .str.contains methode
i have toy dataframe我有玩具数据框
toy_df = pd.DataFrame({'col1': ["apple is green",
"banana is yellow",
"strawberry is red"],
'col2': ["dog is kind",
"cat is smart",
"lion is brave"]})
with output:带输出:
col1 col2
0 apple is green dog is kind
1 banana is yellow cat is smart
2 strawberry is red lion is brave
i have two targets to search, where first is我有两个目标要搜索,第一个是
apple
or lion
and second one is brave
: apple
或lion
,第二个是brave
:
target = 'apple|lion' target2 = 'brave'
i can search with first target easily:我可以轻松搜索第一个目标:
toy_df[toy_df.apply(lambda x: x.str.contains(targets)).any(axis=1)]
outpus is:输出是:
col1 col2
0 apple is green dog is kind
2 strawberry is red lion is brave
but how i shoud search with TWO targets ( target1 and target2
) ?但是我应该如何搜索两个目标(
target1 and target2
)? to get this output:得到这个输出:
col1 col2
2 strawberry is red lion is brave
Use logical AND ( &
) to combine both boolean conditions:使用逻辑AND (
&
) 组合两个布尔条件:
mask1 = toy_df.apply(lambda x: x.str.contains(targets)).any(axis=1)
mask2 = toy_df.apply(lambda x: x.str.contains(target2)).any(axis=1)
toy_df[mask1 & mask2]
[out] [出去]
col1 col2
2 strawberry is red lion is brave
toy_df = pd.DataFrame({'col1': ["apple is green",
"banana is yellow",
"strawberry is red"],
'col2': ["dog is kind",
"cat is smart",
"lion is brave"]})
targets = 'apple|lion'
target2 = 'brave'
mask1 = toy_df.apply(lambda x: x.str.contains(targets)).any(axis=1)
mask2 = toy_df.apply(lambda x: x.str.contains(target2)).any(axis=1)
toy_df[mask1 & mask2]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.