gpt4 book ai didi

python - Pandas 数据框选择列表列包含任何字符串列表的行

转载 作者:太空狗 更新时间:2023-10-29 20:50:52 25 4
gpt4 key购买 nike

我有一个看起来像这样的 pandas DataFrame:

  molecule            species
0 a [dog]
1 b [horse, pig]
2 c [cat, dog]
3 d [cat, horse, pig]
4 e [chicken, pig]

我喜欢提取仅包含那些行的 DataFrame,这些行包含任何 selection = ['cat', 'dog']。所以结果应该是这样的:

  molecule            species
0 a [dog]
1 c [cat, dog]
2 d [cat, horse, pig]

最简单的方法是什么?

用于测试:

selection = ['cat', 'dog']
df = pd.DataFrame({'molecule': ['a','b','c','d','e'], 'species' : [['dog'], ['horse','pig'],['cat', 'dog'], ['cat','horse','pig'], ['chicken','pig']]})

最佳答案

IIUC 重新创建你的 df 然后使用 isinany 应该比 apply 更快

df[pd.DataFrame(df.species.tolist()).isin(selection).any(1).values]
Out[64]:
molecule species
0 a [dog]
2 c [cat, dog]
3 d [cat, horse, pig]

关于python - Pandas 数据框选择列表列包含任何字符串列表的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53342715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com