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
dtypeSeries
而不是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]