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

Pandas如何获取与指定行特定列值一致的所有行?

问题解决:筛选与指定行特征完全匹配的DataFrame行

问题场景

现有Pandas DataFrame filtered,以及列名列表 features,需求是获取所有与索引为0的行在features指定列上值完全相同的行。

错误代码分析

第一段代码报错原因

print(filtered[features].drop_duplicates().iloc[0][features])
print(filtered[filtered[features].eq(filtered[features].drop_duplicates().iloc[0][features]).all()])

报错 IndexingError: Unalignable boolean Series provided as indexer,核心问题是all()默认按列(axis=0)计算,得到的布尔Series索引是列名,和filtered的行索引不匹配,导致无法用于行筛选。必须指定axis=1让all()按行判断是否所有列都匹配。

第二段代码输出全0的可能原因

for idx, row in filtered.iterrows():
    sub_filt = filtered[filtered[sub_features].eq(row[sub_features]).all(axis=1)]
    print(len(sub_filt))
  1. 列名不匹配:如果sub_features不是目标列列表features,自然无法找到匹配行;
  2. 数据类型差异:比如数值类型(int/float)不一致(如5 vs 5.0),或存在NaN值未处理,导致eq()判断不相等;
  3. 基准行错误:iterrows()遍历的行如果本身在sub_features列有唯一值,也会导致无匹配(但预期至少1,所以大概率是前两个原因)。

正确实现代码

# 获取索引为0的行作为基准(无需去重,直接取目标行)
base_row = filtered[features].iloc[0]
# 按行判断所有features列是否与基准行匹配
matching_rows = filtered[filtered[features].eq(base_row).all(axis=1)]
print(matching_rows)

补充说明

  • 如果需要处理NaN值(NaN和NaN默认不相等),可以在eq()中添加equal_nan=True:
    matching_rows = filtered[filtered[features].eq(base_row, equal_nan=True).all(axis=1)]
    
  • 避免使用drop_duplicates().iloc[0],因为去重后原索引0的行可能被移除,导致基准行错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 19:38:35