Skip to main content
 首页 » 编程设计

python之Pandas相当于一对多关系的vlookup,返回一个结果

2025年02月15日7www_RR

当它涉及两个数据框和一对多关系时,我想知道 Excel Vlookup 的 pandas 替代方案。我已经搜索过这个答案,但认为我没有找到可以解决我的用例的答案。下面是一些相关的帖子,但不完全是我需要的。

Excel VLOOKUP equivalent in pandas

vlookup between 2 Pandas dataframes

情况:

我有两个数据框和一个链接两者(站点)的键。我会使用 pandas 合并功能,但我不希望为一个键(本例中的位置 B)返回多条记录。

具体来说,我想从 loc_status 数据框中返回站点的状态(如果它存在)。如果该位置同时具有“非事件”和“事件”状态,那么我只想返回“事件”。

这是一个基本的例子:

loc_status = [{'site':'A', 'status':'ACTIVE'}, {'site':'B',         'status':'ACTIVE'},{'site':'B', 'status':'INACTIVE'},{'site':'C', 'status':'INACTIVE'} ] 
 
loc = [{'site':'A'}, {'site':'B'},{'site':'C'}, {'site':'D'} ] 
 
df_status = pd.DataFrame(loc_status) 
 
+----+-------+----------+ 
|    | site  |  status  | 
+----+-------+----------+ 
| 0  | A     | ACTIVE   | 
| 1  | B     | ACTIVE   | 
| 2  | B     | INACTIVE | 
| 3  | C     | INACTIVE | 
+----+-------+----------+ 
 
df_loc = pd.DataFrame(loc) 
 
+------+---+ 
| site |   | 
+------+---+ 
|   0  | A | 
|   1  | B | 
|   2  | C | 
|   3  | D | 
+------+---+ 
 
result = [{'site':'A', 'status':'ACTIVE'}, {'site':'B', 'status':'ACTIVE'},{'site':'C', 'status':'INACTIVE'}, {'site': 'D'}] 
 
df_result = pd.DataFrame(result) 
 
+----+-------+----------+ 
|    | site  |  status  | 
+----+-------+----------+ 
| 0  | A     | ACTIVE   | 
| 1  | B     | ACTIVE   | 
| 2  | C     | INACTIVE | 
| 3  | D     | NaN      | 
+----+-------+----------+ 

谢谢。

请您参考如下方法:

第一个sort_values通过两列,所以对于每个站点,如果重复 status 总是 ACTIVE 是第一个。那么drop_duplicates使用默认 keep=first - 如果重复,则只获取 ACTIVE。

最后map由使用 set_index 创建的系列 :

df_status = df_status.sort_values(['site','status']).drop_duplicates(['site']) 
print (df_status) 
  site    status 
0    A    ACTIVE 
1    B    ACTIVE 
3    C  INACTIVE 
 
df_loc['status'] = df_loc['site'].map(df_status.set_index('site')['status']) 
print (df_loc) 
  site    status 
0    A    ACTIVE 
1    B    ACTIVE 
2    C  INACTIVE 
3    D       NaN 

时间:

#jezrael solution 
In [136]: %timeit df_loc['status_jez'] = df_loc['site'].map(df_status.sort_values(['site','status']).drop_duplicates(['site']).set_index('site')['status']) 
10 loops, best of 3: 67.3 ms per loop 
 
#Allen solution 
In [137]: %timeit pd.merge(df_loc,df_status.sort_values(['site','status']).groupby(by='site').first().reset_index(),how='left') 
10 loops, best of 3: 114 ms per loop 
 
#piRSquared solution 
In [138]: %timeit df_loc.assign(status_pir=df_loc.site.map(df_status.loc[(df_status.status == 'ACTIVE').groupby(df_status.site).idxmax()].set_index('site').status)) 
1 loop, best of 3: 3.37 s per loop 

计时代码:

np.random.seed(123) 
N = 100000 
L = np.random.randint(100000,size=N) 
df_status = pd.DataFrame({'site': np.random.choice(L, N), 
                         'status':np.random.choice(['ACTIVE','INACTIVE'],N)}) 
print (df_status.head(10)) 
 
df_loc = pd.DataFrame({'site':L}) 
print (df_loc.head(10))