仅在不存在的情况下将行添加到Pandas DataFrame

时间:2019-04-02 16:28:04

标签: python pandas

我正在使用来自webscrapping的数据逐步将行追加到DataFrame。虽然,有时我要抓取的数据已经存在于DataFrame中,所以我不想再次附加它。检查DataFrame是否已经有数据的最有效方法是什么?在结尾处删除重复项不是一种选择,因为我想提取特定数量的记录,而在结尾处删除重复项将使最终DataFrame的记录少于该指定数目。

res = pd.DataFrame([], columns=GD_SCHEMA)

reviews = self.browser.find_elements_by_class_name('empReview')
idx = 0
for review in reviews:
    data = extract_review(review) # This is a dict with the same keys as ´res´

    # Most efficient way to check if ´data´ already exists in ´res´ before appending?
    res.loc[idx] = data
    idx += 1

3 个答案:

答案 0 :(得分:2)

虽然我同意@AndreasT 在组装 DataFrame 之前创建字典更有效,但我仍然感到惊讶的是最初的问题没有答案。似乎您正在寻找的内容可以通过索引交集或差异来简单计算:

res = pd.DataFrame(index = np.arange(100), columns=[1,2])
new_data = pd.DataFrame(index = np.arange(90, 110), columns = [1,2])
already_present_index = res.index.intersection(new_data.index)
missing_index = new_data.index.difference(res.index)

使用 missing_index,您可以决定仅附加来自 new_data 的元素并更新原始框架:

res.append(new_data.loc[missing_index, :])

如果您只有一个新行,您可以通过键入 new_data.index[0] in res.index 直接检查它是否已经在索引中。

如果您的 DataFrame 不是太长并且您不关心覆盖,那么您的 .loc 分配解决方案也应该可以正常工作。

答案 1 :(得分:0)

我建议使用中间字典。如果您明智地选择dict的键,以使重复项的哈希值相等,则将得到一个没有重复项的字典,一旦字典具有所需的长度,就可以将其加载到数据框中。

答案 2 :(得分:0)

我认为您可以将其与数据库进行比较,转换为系列,然后使用.any()函数检查它是否已在数据库中。只是它必须完全相似。根据您的目标,在完整性和重复项的存在之间进行权衡。否则,您可以检查相似率并选择适当的截止值。

    # Most efficient way to check if ´data´ already exists in ´res´ before appending?
     if pd.Series([reviews==res]).any().any().bool():
          pass
     else:
          res.loc[idx] = data
          idx += 1