我很惊讶pandas没有提供本地解决方案来完成这个任务。如果你处理大型数据集(如Rian G建议的),仅仅删除重复项并不高效。
使用集合查找非重叠索引可能是最有效的方法。然后使用列表推导将索引转换为“行位置”(布尔值),您需要使用iloc[,]访问行。下面是一个执行此任务的函数。如果您没有选择要检查重复项的特定列(col),则将使用索引,正如您所请求的那样。如果您选择了特定列,请注意'a'中现有的重复条目将保留在结果中。
import pandas as pd
def append_non_duplicates(a, b, col=None):
if ((a is not None and type(a) is not pd.core.frame.DataFrame) or (b is not None and type(b) is not pd.core.frame.DataFrame)):
raise ValueError('a and b must be of type pandas.core.frame.DataFrame.')
if (a is None):
return(b)
if (b is None):
return(a)
if(col is not None):
aind = a.iloc[:,col].values
bind = b.iloc[:,col].values
else:
aind = a.index.values
bind = b.index.values
take_rows = list(set(bind)-set(aind))
take_rows = [i in take_rows for i in bind]
return(pd.concat([a, b.iloc[take_rows,:]]))
a = pd.DataFrame([[1,2,3],[1,5,6],[1,12,13]], index=[1000,2000,5000])
b = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]], index=[1000,2000,3000])
append_non_duplicates(a,b)
append_non_duplicates(a,b,0)
A = pd.DataFrame({"II": [2, 1]}, index=[1, 3])
。I
列是DataFrame的索引吗? - TomAugspurger