【问题标题】:Combining three datasets removing duplicates结合三个数据集去除重复
【发布时间】:2021-09-16 13:06:39
【问题描述】:

我有三个数据集:

数据集 1

Customer1            Customer2          Exposures  + other columns
Nick McKenzie       Christopher Mill      23450
Nick McKenzie       Stephen Green         23450
Johnny Craston      Mary Shane              12
Johnny Craston      Stephen Green           12
Molly John          Casey Step          1000021

dataset2(唯一客户:客户 1 + 客户 2)

Customer            Age
Nick McKenzie       53
Johnny Craston      75
Molly John          34
Christopher Mill    63
Stephen Green       65
Mary Shane          54
Casey Step          34
Mick Sale   

数据集 3

Customer1            Customer2          Exposures  + other columns
Mick Sale           Johnny Craston           
Mick Sale           Stephen Green        

风险仅针对客户 1。

为简洁起见,省略了其他列。数据集 2 是通过获取唯一客户 1 和唯一客户 2 构建的:该数据集中没有重复项。数据集 3 与数据集 1 具有相同的列。

我想将数据集 1 中的信息添加到数据集 2 中

最终数据集

Customer            Age    Exposures   +   other columns
Nick McKenzie       53       23450
Johnny Craston      75       12
Molly John          34      1000021
Christopher Mill    63
Stephen Green       65
Mary Shane          54
Casey Step          34
Mick Sale

最终的数据集应该包含数据集 1 和数据集 3 中的所有 Customer1 和 Customer 2,并且没有重复。 我尝试将它们组合如下

result = pd.concat([df2,df1,df3], axis=1) 

但结果不是我所期望的。 我连接数据集的方式出了点问题,如果您能告诉我出了什么问题,我将不胜感激。

【问题讨论】:

  • 不幸的是,这个问题没有任何可行的解决方案就关闭了。

标签: python pandas


【解决方案1】:

连接数据帧 df1 和 df2(假设它们具有相同的列)后,我们可以使用 df1.drop_duplicates(subset=['customer1']) 删除重复项,然后我们可以像这样使用 df2 加入

df1.set_index('Customer1').join(df2.set_index('Customer'))

如果df1 和df2 基于主键有不同的列,我们可以使用上述命令加入,然后再次加入age 表。

这将给出结果。您可以连接数据集 1 和数据集 3,因为它们具有相同的列。然后运行此操作以获得所需的结果。我正在加入指定相应的键。

注意:虽然与问题无关,但对于串联可以使用此代码pd.concat([df1, df3],ignore_index=True)(这里我们忽略索引列)

【讨论】:

  • 我正在从 df1 的字段中获取所有 NaN。你知道为什么吗?
  • 但是你没有给我们一个我可以运行的最小示例。如果我的睡眠没有打扰我,这个想法是正确的。如果您创建数据框创建代码(硬编码)并将其粘贴到此处,我可以试一试。
  • @LdM 可能是。通常这就是社区成员要求用户发布示例的原因。从长远来看,它有帮助。一切顺利。
  • @LdM 我没有,因为它是两个数据集中的同一列。因此,如果将 df1 和 df2 (正常合并)结合起来,然后运行上面的代码,它会给出结果。 (除非我遗漏了什么)
  • @LdM 是的,那么您可以轻松地通过合并然后删除主键 (customer1) 上的重复项,然后加入它们以获得 age 列。就是这样。
猜你喜欢
  • 2020-10-13
  • 2012-03-05
  • 2017-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-25
  • 1970-01-01
  • 2012-09-23
相关资源
最近更新 更多