如何在Python中实现类似Excel VLOOKUP的DataFrame匹配功能
解决方案
你需要的是用pandas实现类似Excel VLOOKUP的匹配逻辑,核心是处理Overall_Season_Avg的复合索引,再通过合并或映射完成列的提取:
方法一:使用merge合并(推荐,逻辑清晰)
因为Overall_Season_Avg是通过groupby(['Team_Season_Code', 'Team'])生成的,它的索引是复合索引(包含Team_Season_Code和Team),所以第一步要先把索引转为普通列,再和df做左连接:
# 先重置Overall_Season_Avg的索引,让Team_Season_Code成为普通列 Overall_Season_Avg_reset = Overall_Season_Avg.reset_index() # 合并df和处理后的Overall_Season_Avg,只保留需要的TS、OS列 df = df.merge( Overall_Season_Avg_reset[['Team_Season_Code', 'TS', 'OS']], left_on='Opponent_Season_Code', # df中用于匹配的列 right_on='Team_Season_Code', # Overall_Season_Avg中用于匹配的列 how='left' # 左连接,保留df所有行 ) # 重命名列并删除多余的匹配键列 df = df.rename(columns={'TS': 'OTS', 'OS': 'OOS'}).drop(columns='Team_Season_Code')
方法二:使用map映射(更简洁)
先从Overall_Season_Avg中提取出以Team_Season_Code为键的映射关系,再直接给df赋值新列:
# 重置索引后,创建TS和OS的映射Series ots_mapping = Overall_Season_Avg.reset_index().set_index('Team_Season_Code')['TS'] oos_mapping = Overall_Season_Avg.reset_index().set_index('Team_Season_Code')['OS'] # 给df添加新列 df['OTS'] = df['Opponent_Season_Code'].map(ots_mapping) df['OOS'] = df['Opponent_Season_Code'].map(oos_mapping)
为什么之前的方案不适用?
大概率是因为你忽略了Overall_Season_Avg的复合索引——直接用它的索引列去匹配df的普通列会失败,必须先通过reset_index()把索引转为可直接访问的列,才能正常匹配。
内容的提问来源于stack exchange,提问作者TSned3
相关产品推荐
相关产品推荐

