Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python str.contains methode中的操作和_Python_Pandas - Fatal编程技术网

Python str.contains methode中的操作和

Python str.contains methode中的操作和,python,pandas,Python,Pandas,我有玩具数据框 toy_df = pd.DataFrame({'col1': ["apple is green", "banana is yellow", "strawberry is red"], 'col2': ["dog is kind", "cat is smart",

我有玩具数据框

toy_df = pd.DataFrame({'col1': ["apple is green",
                       "banana is yellow",
                       "strawberry is red"],
                     'col2': ["dog is kind",
                       "cat is smart",
                       "lion is brave"]})
输出:

                 col1           col2
0      apple is green     dog is kind
1    banana is yellow    cat is smart
2   strawberry is red   lion is brave
我有两个目标要搜索,第一个目标在哪里

apple
lion
第二个是勇敢的:

target='apple | lion'
target2=‘勇敢’

我可以轻松搜索第一个目标:

toy_df[toy_df.apply(lambda x: x.str.contains(targets)).any(axis=1)]
输出是:

                 col1            col2
0      apple is green     dog is kind
2   strawberry is red   lion is brave
但是我应该如何搜索两个目标(
target1和target2
)?要获得此输出,请执行以下操作:

                 col1            col2
2   strawberry is red   lion is brave

使用逻辑
&
)组合两个布尔条件:

例子 [外]


更新-完整代码
您的代码有以下错误:
不支持的操作数类型(&:'str'和'str'
什么是
print(mask1.dtype)
print(mask2.dtype)
请?
'DataFrame'对象没有属性'dtype'
确定,因此这不正确,
mask1
mask2
应该是
boolean
dtype
Series
而不是
DataFrame
-您是否明确使用了
.any(axis=1
)并将其放在正确的位置?如果在此代码中需要
.any(axis=1)
,请仔细检查括号。括号是对的。我可以分别打开
mask1
mask2
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]
                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]