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

DataFrame使用Index.get_loc()获整数索引报错,求正确key值

问题描述

我有一个在DataFrame中搜索指定术语的函数,希望返回找到该术语的整数型索引。查阅文档后,我认为Index.get_loc()可以实现需求,但运行代码时出现错误。

我的代码如下:

df = pd.read_excel(os.path.join(MEDIA_ROOT, "files", file), sheet_name=sheet)
for col in df.columns:
    rowfilter = df[col].map(lambda i: str(i)).str.contains("quantity", case=False, regex=False)
    search_row = df[rowfilter].index.get_loc() #This is a 'slice' of the rows containing the search term
    print(search_row)
    #The output should be 6

报错信息:

Index.get_loc() missing 1 required positional argument: 'key'

我尝试了以下代码:

search_row = df[rowfilter].index()
print(pd.Index.get_loc(search_row))

但仍出现相同错误,请问正确的key应该是什么?

解决方案

首先要明确:Index.get_loc(key)的作用是根据传入的key值,返回它在索引中的整数位置,所以必须传入要查找的具体索引值作为key——但你的需求根本不需要用这个方法,直接取过滤后DataFrame的索引即可。

修正后的代码

df = pd.read_excel(os.path.join(MEDIA_ROOT, "files", file), sheet_name=sheet)
for col in df.columns:
    # 用astype(str)替代map,更高效
    rowfilter = df[col].astype(str).str.contains("quantity", case=False, regex=False)
    # 直接获取匹配行的索引,转成列表
    matching_indices = df[rowfilter].index.tolist()
    # 取第一个匹配的索引(即你要的6)
    if matching_indices:
        print(matching_indices[0])

关键说明

  1. df[rowfilter].index直接返回所有匹配行的索引对象,用tolist()可以转成整数列表,直接就能拿到你要的整数索引。
  2. 替换map(lambda i: str(i))为astype(str),功能完全一致但性能更优。
  3. 加个判断if matching_indices是为了避免没有匹配项时报错。

你的代码报错原因

  • 调用index.get_loc()时没传key参数:这个方法需要你指定具体要找的索引值(比如某个行号或标签),不是用来批量获取匹配索引的。
  • df[rowfilter].index()是错误写法:index是DataFrame的属性,不是方法,不需要加括号。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 15:18:03