在Pandas中使用join实现vlookup

45

我有以下两个数据框:

Example1
sku loc flag  
122  61 True 
123  61 True
113  62 True 
122  62 True 
123  62 False
122  63 False
301  63 True 

Example2 
sku dept 
113 a
122 b
123 b
301 c 

我想使用Pandas(或最好的Python操作符)执行合并或连接操作,以生成下面的数据框。

Example3
sku loc flag   dept  
122  61 True   b
123  61 True   b
113  62 True   a
122  62 True   b
123  62 False  b
122  63 False  b
301  63 True   c

Both 
df_Example1.join(df_Example2,lsuffix='_ProdHier')
df_Example1.join(df_Example2,how='outer',lsuffix='_ProdHier')

不能工作。 我做错了什么?

3个回答

84

执行左连接合并,使用 sku 列作为连接的列:

In [26]:

df.merge(df1, on='sku', how='left')
Out[26]:
   sku  loc   flag dept
0  122   61   True    b
1  122   62   True    b
2  122   63  False    b
3  123   61   True    b
4  123   62  False    b
5  113   62   True    a
6  301   63   True    c

如果 sku 确实是您的索引,请执行以下操作:

In [28]:

df.merge(df1, left_index=True, right_index=True, how='left')
Out[28]:
     loc   flag dept
sku                 
113   62   True    a
122   61   True    b
122   62   True    b
122   63  False    b
123   61   True    b
123   62  False    b
301   63   True    c

另一种方法是使用 map,如果您在第二个数据框中将 sku 设置为索引,那么它实际上就变成了一个序列,然后代码就简化为:

In [19]:

df['dept']=df.sku.map(df1.dept)
df
Out[19]:
   sku  loc   flag dept
0  122   61   True    b
1  123   61   True    b
2  113   62   True    a
3  122   62   True    b
4  123   62  False    b
5  122   63  False    b
6  301   63   True    c

6

一个更通用的应用是使用applylambda,如下所示:

dict1 = {113:'a',
         122:'b',
         123:'b',
         301:'c'}

df = pd.DataFrame([['1', 113],
                   ['2', 113],
                   ['3', 301],
                   ['4', 122],
                   ['5', 113]], columns=['num', 'num_letter'])

添加为新的数据框列

 **df['letter'] = df['num_letter'].apply(lambda x: dict1[x])**

  num  num_letter letter
0   1         113      a
1   2         113      a
2   3         301      c
3   4         122      b
4   5         113      a

或者替换现有的('num_letter')列

 **df['num_letter'] = df['num_letter'].apply(lambda x: dict1[x])**

  num num_letter
0   1          a
1   2          a
2   3          c
3   4          b
4   5          a

4

VBA中的VLookup就像pandas.dataframe.merge

过去我总是寻找VBA的许多程序,现在Python的数据框架为我省了大量的工作,好处是我不需要编写vlookup方法。

pandas.DataFrame.merge

>>> A              >>> B
    lkey value         rkey value
0   foo  1         0   foo  5
1   bar  2         1   bar  6
2   baz  3         2   qux  7
3   foo  4         3   bar  8
>>> A.merge(B, left_on='lkey', right_on='rkey', how='outer')
   lkey  value_x  rkey  value_y
0  foo   1        foo   5
1  foo   4        foo   5
2  bar   2        bar   6
3  bar   2        bar   8
4  baz   3        NaN   NaN
5  NaN   NaN      qux   7

您也可以尝试以下方法进行左连接合并。
import pandas as pd
pd.merge(left, right, left_on = 'key', right_on = 'key', how='left')

outerleft的作用类似于SQL,Python内置的DataFrame类有一个merge方法,可以接受多个参数,非常详细和方便。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接