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

pandas行值与列头部分匹配时返回对应列取值的实现方法

解决方法

你的原始代码存在两处核心逻辑偏差:

  • 目标列筛选错误:你需要选择的是前缀为Near_Group_的两列,而非删除名为Red/Blue的列
  • 取值逻辑错误:你之前的代码是匹配列值与Item列值,实际需求是根据Item的取值找到对应列,提取该列的行值

如果仅存在Red/Blue两种取值,最简单的修改方案是直接按条件分支取值:

import pandas as pd
import numpy as np

d = {'Item': ["Red", "Blue", "Blue", "Red"],
     'Near_Group_Red': [0, 0, 0, 0],
     'Near_Group_Blue': [1, 1, 1, 0],
    }
df = pd.DataFrame(data=d)

# 修改后的代码
df['SELECT'] = np.where(df['Item'] == 'Red', df['Near_Group_Red'], df['Near_Group_Blue'])

如果后续可能新增其他类别(比如Green),可以用更通用的方案,自动匹配对应列取值:

# 通用方案:自动拼接目标列名,批量取值
df['SELECT'] = df.reindex('Near_Group_' + df['Item'], axis=1).to_numpy()[df.index, range(len(df))]
# 也可以用兼容旧版pandas的lookup方法
# df['SELECT'] = df.lookup(df.index, 'Near_Group_' + df['Item'])

运行后输出的df完全符合预期:

Item  Near_Group_Red  Near_Group_Blue  SELECT
0   Red               0                1       0
1  Blue               0                1       1
2  Blue               0                1       1
3   Red               0                0       0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 12:45:03