【Python数据处理】两个excel表格数据匹配
【代码】【Python数据处理】两个excel表格数据匹配。
·
两个Excel表格根据列名,进行数据对比
1.单条件匹配(只根据一个列名)
import pandas as pd
df1 = pd.read_excel('数据1.xls', dtype='str')
df2 = pd.read_excel('数据2.xlsx', dtype='str')
# 假设我们根据某个列来匹配两个表格,比如 'ID' 列
# 找出第一个表格中与第二个表格在'ID'列匹配的行
condition = df1['ID'].isin(df2['ID'])
# 将匹配的行对应表格1(表格2)
matched_rows = df1[condition ]
# 将匹配的行导出到新的Excel文件
matched_rows.to_excel('匹配数据.xlsx', index=True)
# 从表格1(表格2)中删除这些匹配的行
df1 = df1[~df1['ID'].isin(df2['ID'])]
# 将修改后的表格1(表格2)导出到新的Excel文件
df1.to_excel('更新后本单位创建2024-1-29.xlsx', index=True)
2.多条件匹配(根据多个列名)
import pandas as pd
df1 = pd.read_excel('表格1.xlsx', dtype='str')
df2 = pd.read_excel('表格2.xlsx', dtype='str')
# 创建唯一标识符列,row代表列名,即表格1中的列名对应表格2中的列名
df1['unique_id'] = df1['row1'] + '_' + df1['row2'] + '_' + df1['row3']
df2['unique_id'] = df2['row4'] + '_' + df2['row5'] + '_' + df2['row6']
# 使用isin方法比较唯一标识符
condition = df1['unique_id'].isin(df2['unique_id'])
# 筛选df1中符合条件的行
df1_matched = df1[condition]
df1_matched.to_excel('匹配数据.xlsx', index=True)
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐
所有评论(0)