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

如何基于{列:值}字典条件获取Pandas DataFrame的行索引?

用字典条件检索Pandas DataFrame的行索引

下面提供三种实用的实现方法,针对你的示例场景都能返回索引[0]:

方法一:isin() + all() 快速筛选

这种方法简洁高效,适合大多数常规场景:

import pandas as pd
test = pd.DataFrame({'col1': [1,2,3,4], 'col2': [2,3,4,5]}, index = [0,1,2,3])
search = {'col1': 1, 'col2': 2}

# 筛选所有列都符合条件的行,提取索引
matching_indices = test[test.isin(search).all(axis=1)].index.tolist()
print(matching_indices)  # 输出: [0]
  • test.isin(search):生成布尔值矩阵,标记每个单元格是否匹配对应列的目标值
  • .all(axis=1):确保整行所有列都满足条件,返回每行的布尔判断结果
  • 最后通过.index.tolist()提取符合条件的索引列表

方法二:逐列筛选取索引交集

适合需要分步验证条件或扩展复杂逻辑的场景:

import pandas as pd
test = pd.DataFrame({'col1': [1,2,3,4], 'col2': [2,3,4,5]}, index = [0,1,2,3])
search = {'col1': 1, 'col2': 2}

# 初始化索引集合为全部行索引
indices = set(test.index)
for col, val in search.items():
    # 逐步缩小索引范围,保留当前列符合条件的索引交集
    indices.intersection_update(test[test[col] == val].index)

matching_indices = list(indices)
print(matching_indices)  # 输出: [0]
  • 用集合的交集操作,每次只保留同时满足当前列条件的索引
  • 逻辑清晰,便于后续添加自定义筛选规则

方法三:query() 动态生成查询语句

适合需要灵活构造查询表达式的场景,支持字符串等特殊值:

import pandas as pd
test = pd.DataFrame({'col1': [1,2,3,4], 'col2': [2,3,4,5]}, index = [0,1,2,3])
search = {'col1': 1, 'col2': 2}

# 将字典转换为query支持的表达式字符串
query_str = ' and '.join([f"{col} == {repr(val)}" for col, val in search.items()])
# 执行查询并提取索引
matching_indices = test.query(query_str).index.tolist()
print(matching_indices)  # 输出: [0]
  • repr(val)会自动处理字符串、特殊字符等,避免语法错误
  • 生成的查询语句可读性强,便于调试

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 20:22:28