Skip to main content
 首页 » 编程设计

python之Pandas 的excel索引匹配

2025年02月15日7shihaiming

这个问题困扰了我一段时间。如何在 python 中实现 =INDEX(A:A,MATCH(E1&F1,B:B&C:C,0))?如果找不到,这将返回错误。

所以我开始使用 pd.merge_asof。但无论哪种方式,我尝试它只会返回错误。

df_3 = pd.merge_asof(df_1, df_2, on=['x', 'y'], allow_exact_matches=False) 

会报错:

pandas.tools.merge.MergeError: can only asof on a key for left 

编辑:

import pandas as pd 
 
df_1 = pd.DataFrame({'x': ['1', '1', '2', '2', '3', '3', '4', '5', '5', '5'],  
                   'y': ['smth1', 'smth2', 'smth1', 'smth2', 'smth1', 'smth2', 'smth1', 'smth1', 'smth2', 'smth3']}) 
df_2 = pd.DataFrame({'x': ['1', '2', '2', '3', '4', '5', '5'],  
                   'y': ['smth1','smth1','smth2','smth3','smth1','smth1','smth3'], 
                   'z': ['other1','other1','other2','other3','other1','other1','other3',]}) 

这是一个示例,我可以在 excel 中使用上面的公式简单地执行此操作并得到类似这样的结果:

x   y       z 
1   smth1   other1 
1   smth2   #NA 
2   smth1   other1 
2   smth2   other2 
3   smth1   #NA 
3   smth2   #NA 
4   smth1   other1 
5   smth1   other1 
5   smth2   #NA 
5   smth3   other3 

那么,有没有一种简单的方法可以在 pandas 中实现 excel 中的 INDEX MATCH 公式?

请您参考如下方法:

让我们用 how='left' 尝试merge:

df_1.merge(df_2, on=['x','y'], how='left') 

输出:

   x      y       z 
0  1  smth1  other1 
1  1  smth2     NaN 
2  2  smth1  other1 
3  2  smth2  other2 
4  3  smth1     NaN 
5  3  smth2     NaN 
6  4  smth1  other1 
7  5  smth1  other1 
8  5  smth2     NaN 
9  5  smth3  other3