【python】pandas匹配拼接两个excel列

在excel处理大量数据匹配过程中,虽然可以使用vlookup,但是数据量超过10万进行批量匹配的时候,效率非常差,因此使用python。经查,发现python通过pandas库的merge可以实现类似于SQL中join的功能,具体参考下文:

https://pandas.pydata.org/pandas-docs/stable/getting_started/comparison/comparison_with_sql.html#compare-with-sql-join

import pandas as pd
import numpy as np

# %%
with pd.ExcelFile('xx.xlsx') as xls:
    df1 = pd.read_excel(xls,'Sheet1')
    df2 = pd.read_excel(xls,'Sheet2')

outer=pd.merge(df1,df2,on='key')

outer.to_excel('outer_function.xlsx',index=False,encoding='utf-8')

最终实现Sheet1和Sheet2基于相同key字段的匹配,拼接。

不知道为啥,上面这个方法做出来总是有多有少,为了按顺序匹配,有遗漏的情况下我也好手动补充,采用了下面的方法,其中,结果的格式和内容顺序以df1为基础,可以方便的直接将遗漏的df1中的数据复制过来补充上。

outer=pd.merge(df1.drop_duplicates(),df2.drop_duplicates(),left_on='链接',right_on='链接',how='outer')

outer.to_excel(r'H:\e\outer_function3.xlsx',index=False,encoding='utf-8')

猜你喜欢

转载自blog.csdn.net/u010472858/article/details/106196854