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

如何用Pandas批量对比带_x/_y后缀的列并生成_change列?

批量对比DataFrame中_x/_y后缀列并生成_change列

核心思路

先从已知的列名列表中提取所有需要对比的列前缀(即去掉_x/_y后的部分),然后通过循环批量处理每组列对,彻底替代重复的自定义函数。


Pandas 实现方案

假设你使用的是Pandas DataFrame,以下是高效的批量处理代码:

1. 提取唯一前缀列表

从列名列表中筛选出带_x/_y的列,提取它们的公共前缀:

# 假设所有列名存储在 cols 列表中
prefixes = list(set(col.replace('_x', '').replace('_y', '') for col in cols if '_x' in col or '_y' in col))

2. 循环生成_change列

遍历每个前缀,对比对应_x和_y列的值,生成标记列:

import pandas as pd

for prefix in prefixes:
    x_col = f"{prefix}_x"
    y_col = f"{prefix}_y"
    # 先确认两列都存在,避免报错
    if x_col in df.columns and y_col in df.columns:
        # 基础版:值相等返回1,不等返回0(注意:NaN和任何值对比都返回False)
        df[f"{prefix}_change"] = (df[x_col] == df[y_col]).astype(int)

3. 处理空值的进阶版

如果需要把两边都是NaN的情况也视为相等,可以调整判断逻辑:

for prefix in prefixes:
    x_col = f"{prefix}_x"
    y_col = f"{prefix}_y"
    if x_col in df.columns and y_col in df.columns:
        # 值相等 或 两边都是空值,都标记为1
        equal_mask = (df[x_col] == df[y_col]) | (df[x_col].isna() & df[y_col].isna())
        df[f"{prefix}_change"] = equal_mask.astype(int)

PySpark 实现方案

如果你的DataFrame是PySpark类型,结合内置函数即可批量处理:

from pyspark.sql import functions as F

# 同样先提取前缀列表
prefixes = list(set(col.replace('_x', '').replace('_y', '') for col in df.columns if '_x' in col or '_y' in col))

for prefix in prefixes:
    x_col = f"{prefix}_x"
    y_col = f"{prefix}_y"
    if x_col in df.columns and y_col in df.columns:
        # 使用when/otherwise实现判断,同时处理空值
        df = df.withColumn(
            f"{prefix}_change",
            F.when((F.col(x_col) == F.col(y_col)) | (F.isnull(x_col) & F.isnull(y_col)), 1).otherwise(0)
        )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 11:07:09