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

求类似pandas.index.get_indexer的函数:匹配存在的某一组列名

解决方案

可以通过先判断哪一组列名存在于当前DataFrame中,再获取对应索引的方式解决这个问题,具体实现如下:

方法一:遍历候选列组

先定义两组可能的列名,然后遍历找到完全存在的那一组:

import pandas as pd

read = pd.read_csv(file, delimiter=',', skiprows=2)

# 定义两组候选列
candidate_cols = [
    ['re:Trc3_S24', 'im:Trc3_S24'],
    ['re:Trc3_S42', 'im:Trc3_S42']
]

# 筛选出存在的列组
target_cols = None
for cols in candidate_cols:
    if all(col in read.columns for col in cols):
        target_cols = cols
        break

# 获取对应索引
column_real, column_im = read.columns.get_indexer(target_cols)

方法二:生成器表达式简化

如果确认每组文件必然存在其中一组列,可以用生成器表达式直接拿到目标列组:

import pandas as pd

read = pd.read_csv(file, delimiter=',', skiprows=2)

candidate_cols = [
    ['re:Trc3_S24', 'im:Trc3_S24'],
    ['re:Trc3_S42', 'im:Trc3_S42']
]

target_cols = next(cols for cols in candidate_cols if all(col in read.columns for col in cols))
column_real, column_im = read.columns.get_indexer(target_cols)

关于tolerance参数的说明

get_indexer的tolerance参数主要用于数值类型的索引匹配(比如浮点型索引的近似匹配),并不适用于字符串列名的精确匹配场景,而且只有当两组列名同时存在时,该参数才会影响匹配优先级,所以对你的场景不起作用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 00:07:14