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

Pandas技术问题:查找数组中与另一数组末尾元素匹配的索引

解决方案:查找数组匹配元素的索引

你用index()失败大概率是因为目标元素不存在时会直接抛出错误,导致整行处理中断。下面是两种贴合你需求的实现方式:

情况1:找MT_array中与FV_array末尾元素匹配的索引

如果需求是严格匹配FV_array最后一个元素在MT_array中的位置,用下面的代码,同时处理元素不存在、数组为空的异常情况:

def get_match_index(row):
    # 先获取FV_array的末尾元素,处理空数组情况
    target = row['FV_array'][-1] if row['FV_array'] else None
    if not target or not row['MT_array']:
        return None  # 空数组或无匹配时返回None,也可以改成-1这类默认值
    try:
        # 返回0-based索引,要是需要1-based就加1
        return row['MT_array'].index(target)
    except ValueError:
        # 目标元素不在MT_array里时返回None
        return None

# 对每行应用函数
mf['Result'] = mf.apply(get_match_index, axis=1)

情况2:匹配MT_array最后一个元素在FV_array中的索引

看你的示例,FV_array末尾是there但MT_array里没有,结果却是2,推测你实际需求可能是找MT_array最后一个元素在FV_array中的索引——对应示例里Doe在FV_array的索引正好是2,代码如下:

def get_last_element_index(row):
    if not row['MT_array'] or not row['FV_array']:
        return None
    last_mt_element = row['MT_array'][-1]
    try:
        return row['FV_array'].index(last_mt_element)
    except ValueError:
        return None

mf['Result'] = mf.apply(get_last_element_index, axis=1)

关键说明

  • index()方法在元素不存在时会抛ValueError,所以必须用try-except捕获异常
  • 先判断数组是否为空,避免取[-1]时触发索引错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 21:55:27