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

如何通过正则匹配获取Pandas DataFrame符合条件的行索引

解决方案

从布尔判断DataFrame提取(推荐)

你生成的布尔DataFrame中,只要某一行存在至少一个True就代表该行匹配到了目标动物,用any(axis=1)按行判断后取索引即可:

import pandas as pd
import re

# 测试数据与正则定义
df = pd.DataFrame({'a':['apple','rhino','gray','horn'],
                   'b':['honey','elephant', 'gray','trunk'],
                   'c':['cheese','lion', 'beige','mane']})
ani_pat = r"rhino|zebra|lion"

# 生成布尔判断DataFrame
mask_df = df.apply(lambda x: x.str.match(ani_pat, flags=re.IGNORECASE))

# 提取匹配的行索引
matched_index = mask_df[mask_df.any(axis=1)].index.tolist()
print(matched_index)
# 输出结果:[1]

从原有nonzero返回结果提取

你之前方案返回的元组第一个元素就是所有匹配项对应的行索引,去重后即可得到不重复的匹配行号:

def findIdx(df, pattern):
    return df.apply(lambda x: x.str.match(pattern, flags=re.IGNORECASE)).values.nonzero()

animal = findIdx(df, ani_pat)
matched_index = pd.unique(animal[0]).tolist()
print(matched_index)
# 输出结果:[1]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 12:57:03