【问题标题】:Python Dataframe prevent duplicates while concatingPython Dataframe 在连接时防止重复
【发布时间】:2021-07-31 10:01:02
【问题描述】:

我有两个数据框。我将它们连接起来制作一个。问题是,在对代码进行故障排除时,我会多次使用相同的 concat 代码。这会产生重复行的数据帧,就像我执行 concat 一样多次。我想阻止它。

我的代码:

rdf = pd.DataFrame({'A':[10,20]},index=pd.date_range(start='2020-05-04 08:00:00', freq='1h', periods=2))
df2 = pd.DataFrame({'A':[30,40]},index=pd.date_range(start='2020-05-04 10:00:00', freq='1h', periods=2))

# Run it first time
rdf= pd.concat([rdf,df2])
# First time result
rdf
                      A
2020-05-04 08:00:00  10
2020-05-04 09:00:00  20
2020-05-04 10:00:00  30
2020-05-04 11:00:00  40

# Run it second time
rdf= pd.concat([rdf,df2])
# second time result produces duplicates
rdf
                      A
2020-05-04 08:00:00  10
2020-05-04 09:00:00  20
2020-05-04 10:00:00  30
2020-05-04 11:00:00  40
2020-05-04 10:00:00  30
2020-05-04 11:00:00  40

我的解决方案:我的方法是正确的新行代码,并通过保留第一个来删除重复项。

rdf= pd.concat([rdf,df2])
rdf.drop_duplicates(keep='first',inplace=True)
rdf
                      A
2020-05-04 08:00:00  10
2020-05-04 09:00:00  20
2020-05-04 10:00:00  30
2020-05-04 11:00:00  40

有没有更好的方法?我的意思是,我们可以在连接时防止这种情况吗?因此,无需编写额外的行代码来删除重复项。

【问题讨论】:

  • 有没有理由将 df2 连接到 rdf 的末尾两次?这不会总是导致 df2 的所有行都在 rdf 末尾重复吗?
  • @HenryEcker 我在这里展示了演示。实际上,我在故障排除时多次运行代码,如我的 q 中所述。

标签: python pandas dataframe datetime


【解决方案1】:

那我们试试combine_first

rdf = rdf.combine_first(df2)
rdf = rdf.combine_first(df2)
rdf
Out[115]: 
                        A
2020-05-04 08:00:00  10.0
2020-05-04 09:00:00  20.0
2020-05-04 10:00:00  30.0
2020-05-04 11:00:00  40.0

【讨论】:

  • 非常感谢您介绍这一点。我在这里第一次听到combine_first。万分感谢。这与concat 有何不同?我们可以一直使用它吗?
  • @Mainland concat , 是 append , combine_first , 是查找索引, 将 df2 中缺少的一个添加到 df1 ~
  • 还有一个问题:我可以一直使用combine_first,而直接放弃concat吗?
  • @Mainland 如果你需要更新现有索引并更新新​​索引,你可以做 combine_first,如果你想追加任何你需要的新 df,你的情况答案是肯定的跨度>
猜你喜欢
  • 2014-04-10
  • 2021-08-06
  • 2013-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-14
  • 2014-11-21
  • 1970-01-01
相关资源
最近更新 更多