[英]How to use pandas.to_sql but only add row if row doesn't exist yet
[英]Add row to Pandas DataFrame only if it doesn't exist
我正在逐步将行附加到 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
尽管我同意 @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
键入new_data.index[0] in res.index
来直接检查它是否已经在索引new_data.index[0] in res.index
。
如果您的 DataFrame 不是太长并且您不关心覆盖,那么您的.loc
分配解决方案也应该可以正常工作。
我建议使用中间字典。 如果您明智地选择 dict 的键,以便重复项的哈希值相等,您将获得一个没有重复项的字典,然后您可以在达到所需长度后将其加载到数据帧中。
我认为您可以将它与数据库进行比较,转换为一个系列,然后使用 .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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.