代码示例:
假设有两个表格A和B,每个表格都包含两列(列名分别为"ID"和"Value"),任务是将A中的每一行与B中的每一行匹配,并将匹配的结果输出到一个新表格C中。
Python示例代码:
import pandas as pd
df_a = pd.read_excel("A.xlsx") df_b = pd.read_excel("B.xlsx")
def match(row_a, row_b): # 计算两行Value的和 sum_a = row_a["Value1"] + row_a["Value2"] sum_b = row_b["Value1"] + row_b["Value2"] # 如果ID相同且Value之和也相同,则匹配成功 if row_a["ID"] == row_b["ID"] and sum_a == sum_b: return {"ID": row_a["ID"], "ValueA": sum_a, "ValueB": sum_b} else: return None
matches = [] for index_a, row_a in df_a.iterrows(): for index_b, row_b in df_b.iterrows(): result = match(row_a, row_b) if result: matches.append(result) df_c = pd.DataFrame(matches)
df_c.to_excel("C.xlsx", index=False)