如何在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)
输出结果与你期望的完全一致:
| customer | colour_green | colour_blue | colour_red | brand_a | brand_b | brand_c | max_clr | max_brd |
|---|---|---|---|---|---|---|---|---|
| cust_1 | 2 | 5 | 3 | 6 | 2 | 2 | blue | a |
| cust_2 | 1 | 3 | 4 | 3 | 3 | 2 | red | a,b |
| cust_3 | 7 | 3 | 5 | 2 | 5 | 10 | green | c |
扩展说明
如果后续有更多前缀类别(比如size_、material_),只需重复调用get_top_feature函数即可,无需修改核心逻辑,完全适配大量前缀列的场景。
内容的提问来源于stack exchange,提问作者python_new
相关产品推荐
相关产品推荐

