如何通过传递dataframe列从另一个dataframe列中搜索索引

2024-05-19 10:54:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个数据帧df1和df2

df1
index     emp_id     name         code 
  0          07       emp07        'A'      
  1          11       emp11        'B'      
  2          30       emp30        'C'  

df2
index       emp_id   salary 
     0      06       1000            
     1      17       2000             
     2      11       3000

我想存储从df1['emp_id']df2.index的映射

示例:输入数组-['emp11','B'](来自df1)

预期输出:[11, 2] # this is df1['emp_id'], df2.index

我正在尝试的代码:

columns_to_idx = {emp_id: i for i, emp_id in 
    enumerate(list(DF1.set_index('emp_id').loc[DF2.index][['name', 'code']]))}

Tags: 数据nameid示例indexcode数组this
1条回答
网友
1楼 · 发布于 2024-05-19 10:54:39

我认为您需要^{}与内部联接,以及^{}作为索引中的列,以避免丢失它:

df = df1.merge(df2.reset_index(), on='emp_id')
print (df)
   emp_id   name code  index  salary
0      11  emp11   B      2    3000

然后可以创建MultiIndex并按元组选择:

df2 = (df1.merge(df2.reset_index(), on='emp_id')
         .set_index(['name','code'])[['emp_id','index']])
print (df2)
            emp_id  index
name  code               
emp11 B         11      2

print (df2.loc[('emp11','B')].tolist())
[11, 2]

相关问题 更多 >

    热门问题