- 应用说明
比较B Excel表和A Excel表里的某列数据,以B Excel表为基准,只保留A Excel表里不存在的数据。
- 代码示例
import pandas as pd
def compare_and_delete_rows(file_a, file_b, column_name, output_file):
try:
# 读取 A 表和 B 表的数据
df_a = pd.read_excel(file_a)
df_b = pd.read_excel(file_b)
# 提取 A 表指定列的数据
values_in_a = df_a[column_name].tolist()
# 过滤 B 表,只保留指定列中不在 A 表中的行
df_b = df_b[~df_b[column_name].isin(values_in_a)]
# 将处理后的 B 表数据保存到新的 Excel 文件中
df_b.to_excel(output_file, index=False)
print(f"处理完成,结果已保存到 {output_file}")
except FileNotFoundError:
print("错误: 文件未找到,请检查文件路径。")
except KeyError:
print(f"错误: 指定的列名 {column_name} 不存在于文件中。")
except Exception as e:
print(f"发生未知错误: {e}")
if __name__ == "__main__":
# 请根据实际情况修改这些参数
file_a = r'D:\translateZ.xlsx'
file_b = r'D:\translateB.xlsx'
column_name = '中文'
output_file = r'D:\translateC.xlsx'
compare_and_delete_rows(file_a, file_b, column_name, output_file)