【问题标题】:Map some columns of a data frame to other based on two column match pandas [duplicate]基于两列匹配熊猫将数据框的某些列映射到其他列[重复]
【发布时间】:2020-05-31 13:28:12
【问题描述】:

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

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 的 Usage 和 Type 列,基于 Sector,Plot 匹配。

预期输出:

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')

【问题讨论】:

    标签: pandas pandas-groupby


    【解决方案1】:

    添加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
    

    【讨论】:

      猜你喜欢
      • 2016-01-27
      • 1970-01-01
      • 2020-10-04
      • 2017-03-03
      • 2021-11-19
      • 1970-01-01
      • 2022-01-06
      • 2020-12-13
      • 2020-11-18
      相关资源
      最近更新 更多