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

Python基于带ELSE的复杂字典为pandas DataFrame新增列的实现方法

Pandas 多列按规则值重映射实现方法

首先拆分映射字典为匹配规则和默认返回值:

# 拆分映射规则与ELSE默认值
map_rules = {k:v for k,v in dic.items() if k != "ELSE"}
default_val = dic.get("ELSE", "")

方法1:逐行扫描实现(易理解,适合小数据量)

按指定校验列的顺序逐行匹配,命中即返回对应映射值,全部无命中返回默认值:

def row_mapper(row):
    for col in cols_to_check:
        current_val = row[col]
        # 跳过空值、NaN、空白字符串
        if pd.isna(current_val) or str(current_val).strip() == "":
            continue
        stripped_val = str(current_val).strip()
        if stripped_val in map_rules:
            return map_rules[stripped_val]
    return default_val

df["Result"] = df.apply(row_mapper, axis=1)

方法2:向量化实现(高性能,适合10万行以上大数据量)

# 堆叠待检查列,批量映射后按行取第一个有效匹配结果
stacked_vals = df[cols_to_check].stack().str.strip().map(map_rules)
df["Result"] = stacked_vals.groupby(level=0).first().reindex(df.index, fill_value=default_val)

运行后得到的Result列输出如下:

IDResult
AB01Type dual
AB02Type dual
AB03Type many
AB04Not listed
AB05Type dual
AB06Not listed
AB07Not listed
AB08Type dual

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 17:18:02