vlookup 相当于使用 Pandas 连接 2 个表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30905573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:28:50  来源:igfitidea点击:

vlookup equivalent to join 2 tables using pandas

pythonjoinpandasdataframevlookup

提问by Justin Pines

Scenario:

设想:

  • df1 has all possible auction ID values
  • df2 has a subset of possible auction ID values
  • df2 contains the object ID present in the auction (can be 0 or positive int)
  • df1 具有所有可能的拍卖 ID 值
  • df2 有一个可能的拍卖 ID 值的子集
  • df2 包含拍卖中存在的对象 ID(可以是 0 或正整数)

Goal:

目标:

Create a new df1 column "object_id" populated with corresponding values in df2

创建一个新的 df1 列“object_id”,用 df2 中的相应值填充

Example...

例子...

df1 = pd.DataFrame(columns=['auction_id'], data=[1,2,3,4,5,6,7,8,9])

auction_id
1  
2  
3  
4  
5  
6  
7  
8  
9  


df2 = pd.DataFrame({'auction_id':[1,2,4,6,7,8,9], 'object_id': [640,0,332,332,0,58,332]})

auction_id  object_id  
1             640  
2             0  
4             332  
6             332  
7             0  
8             58  
9             332  

My best effort so far

迄今为止我的最大努力

using vlookup in Pandas using join):

使用VLOOKUP在Pandas使用连接):

df1['object_id'] = df1.auction_id.map(df2.object_id)

Which yields:

其中产生:

df1  
auction_id  object_id
1             0  
2             332  
3             332  
4             0  
5             58  
6             332  
7             NaN  
8             NaN  
9             NaN  

回答by cerod

You can use the merge function from the pandas library as follows:

您可以使用 pandas 库中的合并功能,如下所示:

import pandas as pd

df1 = pd.DataFrame(columns=['auction_id'], data=[1,2,3,4,5,6,7,8,9])    
df2 = pd.DataFrame({'auction_id':[1,2,4,6,7,8,9], 'object_id': [640,0,332,332,0,58,332]})    

new_df = pd.merge(df1,df2,how='left',on='auction_id')

You can read about the merge function here: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html

您可以在此处阅读有关合并功能的信息:http: //pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html