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

如何查找pandas DataFrame中特定值对应的行索引与列名

pandas定位DataFrame中指定值的行索引与列名

通过逐元素等值匹配即可快速获取目标值对应的行索引、列名信息,可直接复用以下实现:

import pandas as pd

# 构造示例DataFrame
data = {
   "calories": [420, 380, 390],
   "duration": [50, 40, 45]
}
df = pd.DataFrame(data)

def find_target_position(df, target_value):
    # 生成逐元素匹配的布尔掩码
    match_mask = df.eq(target_value)
    match_result = []
    # 遍历列提取命中的行索引
    for col in match_mask.columns:
        hit_rows = match_mask[match_mask[col]].index.tolist()
        for row_idx in hit_rows:
            match_result.append(f"{row_idx}, {col}")
    # 单条命中直接返回字符串,多条命中返回结果列表
    return match_result[0] if len(match_result) == 1 else match_result

# 测试查找值为40的位置
print(find_target_position(df, 40))

运行上述代码,输出结果和预期一致:

1, duration

补充说明

  • 上述实现默认做严格类型匹配,数值类型的40和字符串类型的"40"不会被判定为匹配;如果需要忽略类型,可以将匹配逻辑替换为match_mask = df.astype(str).eq(str(target_value))
  • 如果目标值在DataFrame中存在多处匹配,函数会返回所有命中位置组成的列表
  • 如果需要查找空值、异常值等特殊值,只需要将传入的target_value替换为对应目标即可,比如查找空值传None或者pd.NA

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 05:00:49