根据两列匹配的熊猫将数据框的某些列映射到其他列

时间:2020-02-16 12:33:44

标签: pandas pandas-groupby

我有两个数据框,如下图所示

df1:

Sector     Plot    Price     Count
A          1       250       2
A          2       100       1
A          3       250       3

df2:

Sector     Plot    Usage    Type
A          1       R        Land
A          1       R        Land
A          2       C        Villa       
A          3       R        Plot
A          3       R        Plot
A          3       R        Plot

根据上面的内容,我想根据扇区,图匹配将df2的“用法和类型”列添加到df1。

预期输出:

Sector     Plot    Price     Count   Usage    Type
A          1       250       2       R        Land
A          2       100       1       C        Villa
A          3       250       3       R        Plot

我尝试了以下代码

df3 = pd.merge(df1, df2, left_on = ['Sector', 'Plot'], 
                     right_on = ['Sector', 'Plot'], how = 'inner')

1 个答案:

答案 0 :(得分:4)

添加DataFrame.drop_duplicates是因为第二个DataFrame中有重复项:

df3 = pd.merge(df1, 
               df2.drop_duplicates(['Sector', 'Plot']), 
               on = ['Sector', 'Plot'])
print (df3)
  Sector  Plot  Price  Count Usage   Type
0      A     1    250      2     R   Land
1      A     2    100      1     C  Villa
2      A     3    250      3     R   Plot