Pandas 数据框选择列表列包含特定元素集的行
这是对以下职位的后续行动: 我希望能够从选择列表中选择包含精确字符串对的行(其中selection=['cat','dog']) 启动df:Pandas 数据框选择列表列包含特定元素集的行,pandas,string,list,Pandas,String,List,这是对以下职位的后续行动: 我希望能够从选择列表中选择包含精确字符串对的行(其中selection=['cat','dog']) 启动df: molecule species 0 a [dog] 1 b [horse, pig] 2 c [cat, dog] 3 d [cat, horse, pig] 4 e [chicken, pig]
molecule species
0 a [dog]
1 b [horse, pig]
2 c [cat, dog]
3 d [cat, horse, pig]
4 e [chicken, pig]
我想要:
molecule species
2 c [cat, dog]
我尝试了以下操作,它只返回了列标签
df[pd.DataFrame(df.species.tolist()).isin(selection).all(1)]
一种方法是:
df['joined'] = df.species.str.join(sep=',')
selection = ['cat,dog']
filtered = df.loc[df.joined.isin(selection)]
这将不会发现具有不同排序的案例(即狗、猫或马、猫、猪),但如果这不是问题,则它可以正常工作