我想从数据帧中删除重复项。如果'summary'列中的30个字符匹配,我认为2行是重复的。
所以我有最长的公共后续函数:
def lcs(X, Y, th=30):
'''X, Y- strings
th-threshold '''
m=len(X)
n=len(Y)
if m<th or n<th:
if X==Y:
return True
else:
return False
LCSuff = [[0 for k in range(n+1)] for l in range(m+1)]
result = 0
for i in range(m + 1):
for j in range(n + 1):
if (i == 0 or j == 0):
LCSuff[i][j] = 0
elif (X[i-1] == Y[j-1]):
LCSuff[i][j] = LCSuff[i-1][j-1] + 1
result = max(result, LCSuff[i][j])
if result>=th:
return True
else:
LCSuff[i][j] = 0
return False 我有另一个函数可以使用上面的lcs()函数来删除重复项:
def remove_duplicates(dataframe, th=30):
df=dataframe.copy()
#create a new empty DataFrame
distinct=pd.DataFrame(columns=df.columns)
distinc=distinct.append(df.loc[0])
while len(df)>0:
#add a new row to distinct df
distinct=distinct.append(df.loc[0], ignore_index=True)
text=df.loc[0,'summary']
indicies=[]
for i in range(len(df)):
text2=df.loc[i, 'summary']
if lcs(text, text2, th):
indicies.append(i)
df=df.drop(indicies)
df=df.reset_index(drop=True)
return distinct该函数可以使用以下示例数据进行测试,其中只考虑10个字符匹配:
d={'summary':['OldText:theTextOld', 'NewText:theTextNew', 'someText', 'someTextOther', 'someOtherT:theTextNew', 'someText']}
data=pd.DataFrame(d)
remove_duplicates(data, 10)对于大约3000行的数据帧,运行这个函数几乎需要一个小时。如何使用pandas apply()函数改进代码?
发布于 2020-08-25 07:33:08
可以做两件事来改变结构...您将无法对此使用apply(),因为您正在将每个元素相互比较。
summary,并通过你的复制查找器运行它,然后在你想要删除的地方生成一个布尔“标记”的推论列表。将该系列追加到数据框中,并使用它一次删除所有重复项。在一个只有大约3000字的框架上,这应该是相当快的。
https://stackoverflow.com/questions/63563085
复制相似问题