我有一只熊猫DataFrame,它看起来像这样:
molecule species
0 a [dog]
1 b [horse, pig]
2 c [cat, dog]
3 d [cat, horse, pig]
4 e [chicken, pig]我喜欢提取一个只包含这些行的DataFrame,它只包含选择=‘狗’。结果应该是这样的:
molecule species
0 a [dog]做这件事最简单的方法是什么?
用于测试:
selection = ['dog']
df = pd.DataFrame({'molecule': ['a','b','c','d','e'], 'species' : [['dog'], ['horse','pig'],['cat', 'dog'], ['cat','horse','pig'], ['chicken','pig']]})我只能找出哪些选项可以提取列表中包含狗的任何列。
发布于 2022-10-31 07:46:00
您可以比较集合,它返回列表与一个或多个只有dog值的列表:
df1 = df[df['species'].apply(lambda x: set(x) == set(selection))]
print (df1)
molecule species
0 a [dog]如果需要,只选择一个值[dog]使用:
df2 = df[df['species'].astype(str).eq(str(selection))]
print (df2)
molecule species
0 a [dog]https://stackoverflow.com/questions/74260113
复制相似问题