Python pandas比对两Excel表列 新增标记列并追加缺失行
两Excel表基于Col1比对的pandas实现方案
前置依赖
先安装读写Excel需要的库,执行命令:pip install pandas openpyxl
完整实现代码
import pandas as pd # 读取两个工作表,注意替换为你本地的实际文件路径、工作表名 # 读取时统一将Col1转为字符串类型,避免跨表类型不匹配导致匹配失败 df_a = pd.read_excel("你的源文件.xlsx", sheet_name="A", dtype={"Col1": str}) df_b = pd.read_excel("你的源文件.xlsx", sheet_name="B", dtype={"Col1": str}) # 处理A表Col3列的赋值逻辑 b_col1_unique = set(df_b["Col1"].dropna().unique()) df_a["Col3"] = df_a["Col1"].apply(lambda x: "YES" if x in b_col1_unique else "NO") # 提取B表独有的Col1条目,追加到A表末尾 a_col1_unique = set(df_a["Col1"].dropna().unique()) b_only_items = df_b[~df_b["Col1"].isin(a_col1_unique)][["Col1"]].drop_duplicates(subset=["Col1"]) df_final = pd.concat([df_a, b_only_items], ignore_index=True) # 导出最终结果,替换为你要保存的文件路径 df_final.to_excel("比对结果.xlsx", index=False)
之前np.where、isin方法报错的常见原因
- 列名存在隐藏的空格、换行符:比如实际列名是
Col1(末尾带空格),直接引用df["Col1"]会触发KeyError,读表后可以执行print(df_a.columns)打印列名核对 - 两表Col1列数据类型不一致:比如A表Col1存的是数字、B表存的是同内容的文本,会导致isin匹配失效,代码里读取时指定
dtype={"Col1": str}就是为了规避这个问题 - 未处理空值:Col1列如果存在NaN空值,直接做逻辑判断容易触发类型错误,代码里匹配前先用
dropna()过滤了空值
示例数据验证
用提供的测试数据运行代码,输出结果完全符合要求:
| Col1 | Col2 | Col3 |
|---|---|---|
| Dog | Apple | YES |
| Cat | Banana | YES |
| Bear | Hotdogs | YES |
| Wolf | Lollipop | NO |
| Hamburger | 空 | 空 |
内容的提问来源于stack exchange,提问作者Yukarii
相关产品推荐
相关产品推荐

