python - 选择 pandas dframe 中的行,其中给定的输入列表是 dframe 列中列表的子集

标签 python pandas

假设我有一个像这样的 pandas dframe :

Name Nos
Jack [4,2,3,12]
Adam [5,6,4,2,3]
John [1,3,4]

最快的方法是什么(简短代码),当输入为 [4,2,3] 时,结果应该是包含行 Jack 和 Adam 的 dframe ?我尝试过使用 where,但我不太能得到正确的解决方案。

最佳答案

如果您需要让值[4, 2, 3]连续出现在列表中,您可以使用以下代码:

input_list = [4, 2, 3]
def func(df, l):
    return df[df['Nos'].astype(str).str.contains(str(l)[1:-1])]
print(func(df, input_list))

如果您只想将值放在那里,请使用:

input_list = [4, 2, 3]
def func(df, l):
    return df[df['Nos'].astype(str).str.contains('&'.join(l))]
print(func(df, input_list))

关于python - 选择 pandas dframe 中的行,其中给定的输入列表是 dframe 列中列表的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59871960/

相关文章:

python - Scipy.optimize COBYLA 约束违规

python - GroupBY 频率计数 JSON 响应 - 嵌套字段

python - Pandas 合并两个具有相同结构的数据框

python - 如何查找两列中的值是否在 Pandas 数据框中反向出现

python - DJango 休息框架中的员工休假类型条件

python - 在 python 中与 selenium 同时抓取

python:使用引用图像和来自相机的当前图像查找相机偏移角度

python - 喀拉斯 : TypeError: 'AddNL' object has no attribute '__getitem__'

python - 列出索引超出范围与 Pandas read_csv

python - 在 Pandas 中将元组设置为列名