简体   繁体   English

查找 excel 到 pandas python

[英]vlookup excel to pandas python

In excel if we want to use VLOOKUP on new column, we need to define lookup value, table array & index column number that we need and then the value fill the column that we need.在 excel 中,如果我们想在新列上使用 VLOOKUP,我们需要定义我们需要的查找值、表数组和索引列号,然后该值填充我们需要的列。 If we want to do it the same with python, how we execute this?如果我们想对 python 做同样的事情,我们如何执行呢?

for example, first and second dataframe例如第一个和第二个 dataframe

data01 = pd.DataFrame({'Code Id':['AA-103', 'BB-203', 'CC-303', 'DD-403'], 'Area':['AA', 'BB', 'CC', 'DD'], 'Sub-Area':['AA', 'BB', 'CC-1', 'DD-3']})
data02 = pd.DataFrame({'Code Id':['AA-103', 'BB-203', 'CC-505', 'FF-606'], 'Area':['AA', 'BB', 'EE', 'FF']})

and then the expected output such a like this然后是预期的 output 这样的

data03 = pd.DataFrame({'Code Id':['AA-103', 'BB-203', 'EE-505', 'FF-606'], 'Area':['AA', 'BB', 'EE', 'FF'], 'Sub-Area':['AA', 'BB', 'Na', 'Na']})

so it's like we put new column in second dataframe based on new contract, not make a new dataframe based both of them.所以就像我们根据新合同在第二个 dataframe 中添加新列,而不是基于两者创建新的 dataframe。 Any idea?任何想法?

One of the ways to do it is to use pandas.merge with a left-join:其中一种方法是将pandas.merge与左连接一起使用:

Left join : It provides all the rows from the first dataframe and will match rows from the second dataframe.左连接:它提供第一个 dataframe 中的所有行,并将匹配第二个 dataframe 中的行。 Every row not found/matched in the second dataframe will be replaced by NaN ( vlookup() will put #N/A instead).在第二个 dataframe 中找不到/匹配的每一行都将被 NaN 替换( vlookup vlookup()将改为 #N/A )。

data03 = data02.merge(data01[['Code Id', 'Sub-Area']], on='Code Id', how='left')

>>> print(data03)

在此处输入图像描述

Note: there is a small error in your data02 , the third Code Id has to equal 'EE-505' and not 'CC-505'.注意:您的data02中有一个小错误,第三个Code Id必须等于“EE-505”而不是“CC-505”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM