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

Pandas如何编写自定义函数实现输入指定行值返回对应行号

Pandas根据列值匹配对应行号的函数实现

核心实现思路是通过布尔索引筛选出目标列值等于输入参数的行,直接取DataFrame的原生索引即可,pandas默认整数索引从0开始计数,和你给出的示例预期(传入nick返回1)的计数规则一致。
注意原示例数据里存储的姓名是全小写格式(nick),如果需要支持传入大小写不一致的参数(比如首字母大写的Nick)也能匹配,可以加统一大小写转换的逻辑。

基础版本(大小写精确匹配)

import pandas as pd

# 初始化示例数据集
data = [['tom', 10], ['nick', 15], ['juli', 14]]
df = pd.DataFrame(data, columns=['Name', 'Age'])

def get_row_num(input_name, ref_df=df, match_col='Name'):
    # 筛选所有匹配的行索引
    match_res = ref_df.index[ref_df[match_col] == input_name].tolist()
    # 无匹配结果时返回None
    if not match_res:
        return None
    # 存在多个匹配结果时默认返回第一个匹配的行号
    return match_res[0]

调用示例:

  • 执行get_row_num('nick'),返回结果为1,符合预期。

兼容大小写的版本

如果需要忽略大小写匹配(比如传入Nick、NICK都能匹配到nick对应的行),使用下面的实现即可:

def get_row_num_ignore_case(input_name, ref_df=df, match_col='Name'):
    match_res = ref_df.index[ref_df[match_col].str.lower() == input_name.lower()].tolist()
    if not match_res:
        return None
    return match_res[0]

调用示例:

  • 执行get_row_num_ignore_case('Nick'),返回结果为1,和你给出的示例要求完全一致。

补充说明:如果你的数据中存在重复的姓名值,需要返回所有匹配行的行号,只需要把函数里的return match_res[0]修改为return match_res即可,此时返回值是所有匹配行号组成的列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 06:27:24