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列输出如下:
| ID | Result |
|---|---|
| AB01 | Type dual |
| AB02 | Type dual |
| AB03 | Type many |
| AB04 | Not listed |
| AB05 | Type dual |
| AB06 | Not listed |
| AB07 | Not listed |
| AB08 | Type dual |
内容的提问来源于stack exchange,提问作者Fazli
相关产品推荐
相关产品推荐

