【问题标题】:Match columns of two dataframe and if matched then get the respective columns from 1st dataframe匹配两个数据帧的列,如果匹配,则从第一个数据帧中获取相应的列
【发布时间】:2020-07-16 17:48:48
【问题描述】:

我有两个数据框:

df1:

和df2:

我想将df1 中的col1df2 中的col_new 匹配。如果它们匹配,那么我想从df1 中提取第一个label。 我想要的输出是:

我正在使用以下代码:

out = (df1.merge(df2, left_on='col1', right_on='col_new'))

但它正在创建更多的记录,因为有多个标签分配给单个值。

【问题讨论】:

  • 使用drop_duplicates 删除重复项。
  • 收到此错误AttributeError: 'Series' object has no attribute 'merge'

标签: python python-3.x pandas


【解决方案1】:

试试这个:

out = (df1.drop_duplicates('col1').merge(df2, left_on='col1', right_on='col_new'))

如果有重复,假设只保留 df1 中的第一个值。

【讨论】:

    猜你喜欢
    • 2020-10-09
    • 2021-03-10
    • 2021-04-03
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-28
    相关资源
    最近更新 更多