You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何以最Pythonic的方式判断列表字符串是否存在于Pandas DataFrame并打印结果?

解决方案

核心思路

针对数千级别的搜索词,优先用**集合(set)**做成员判断——集合的查找效率为O(1),远高于遍历DataFrame的方式,能大幅提升处理性能。

完整代码

import pandas as pd

# 初始化DataFrame
color = ['red', 'blue', 'yellow', 'green']
count = [15, 39, 40, 21]
input_df = pd.DataFrame({'color': color, 'count': count})

# 目标搜索词列表
search_terms = ["red", "blue", "green", "orange"]

# 将DataFrame的color列转为集合,用于快速查找
color_set = set(input_df['color'])

# 遍历输出每个搜索词的存在状态
for term in search_terms:
    print(f"{term} = {'true' if term in color_set else 'false'}")

代码说明

  1. 集合转换:set(input_df['color'])提取DataFrame中所有颜色值并去重,生成一个高效查找的集合结构。
  2. 快速判断:通过term in color_set完成常数时间的存在性检查,遍历所有搜索词即可按要求输出结果。
  3. 性能适配:即使搜索词数量达到数千级,这种方法的处理速度也远优于反复调用isin的方式,避免了不必要的DataFrame遍历开销。

输出结果

red = true
blue = true
green = true
orange = false

内容的提问来源于stack exchange,提问作者Trey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 15:36:28