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

如何在Pandas DataFrame中获取特定前缀列的最大值及对应列名

解决方案

先解决列索引报错问题

你之前遇到的AttributeError: Can only use .str accessor with Index, not MultiIndex,是因为DataFrame的列是多级索引(MultiIndex),而.str方法仅支持普通单层索引。先把多级索引转成单层字符串索引:

# 把多级列名用下划线拼接成单层(比如('colour', 'green')转成'colour_green')
df.columns = ['_'.join(col) for col in df.columns]

通用函数实现批量提取最高得分特征

写一个可复用的函数,传入前缀(比如colour_、brand_)就能自动提取每行得分最高的特征,支持多个并列最高分的情况:

def get_top_feature(df, prefix):
    # 筛选所有带目标前缀的列
    target_cols = [col for col in df.columns if col.startswith(prefix)]
    # 获取每行的最高分
    row_max = df[target_cols].max(axis=1)
    # 提取每行中等于最高分的特征名称(去掉前缀),用逗号连接多个结果
    return df[target_cols].apply(
        lambda row: ','.join([col.split('_')[1] for col in row[row == row_max.loc[row.name]].index]),
        axis=1
    )

调用函数生成目标列

以你的示例数据为例,执行以下代码即可得到期望的结果:

import pandas as pd

# 构造示例数据
data = {
    'customer': ['cust_1', 'cust_2', 'cust_3'],
    'colour_green': [2, 1, 7],
    'colour_blue': [5, 3, 3],
    'colour_red': [3, 4, 5],
    'brand_a': [6, 3, 2],
    'brand_b': [2, 3, 5],
    'brand_c': [2, 2, 10]
}
df = pd.DataFrame(data)

# 新增最高得分颜色列
df['max_clr'] = get_top_feature(df, 'colour')
# 新增最高得分品牌列
df['max_brd'] = get_top_feature(df, 'brand')

# 查看最终结果
print(df)

输出结果与你期望的完全一致:

customercolour_greencolour_bluecolour_redbrand_abrand_bbrand_cmax_clrmax_brd
cust_1253622bluea
cust_2134332reda,b
cust_37352510greenc

扩展说明

如果后续有更多前缀类别(比如size_、material_),只需重复调用get_top_feature函数即可,无需修改核心逻辑,完全适配大量前缀列的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 01:49:50