gpt4 book ai didi

python - 在Python中删除数据框中的重复行

转载 作者:行者123 更新时间:2023-12-01 09:09:21 25 4
gpt4 key购买 nike

我有一个包含 27949 行和 7 列的数据框,前几行如下所示 /image/1Pipf.png

任务:在数据框中,我有一个“标题”列,其中有许多重复的标题,我想删除它们(重复标题:除了 1 或 2 个单词之外,几乎所有标题都是相同的)。伪代码:我想检查第一行和所有其他行,如果其中任何一行是重复的,我想将其删除。然后我想检查第二行和所有其他行,如果其中任何一个是重复的,我想将其删除 - 与所有行类似,即 i = 第一行到最后一行 j = i+1 到最后一行。我的代码:

for i in range(0,27950):
for j in range(1,27950):
a = data_sorted['title'].iloc[i].split()
b = data_sorted['title'].iloc[j].split()
if len(a)-len(b)<=2:
data_sorted.drop(b)
j=j
else:
j+=1
i+=1

错误:IndexError:单个位置索引器超出范围

任何人都可以帮我解决我的代码吗?提前致谢。

最佳答案

我建议采用以下方法:

构建标题的差异矩阵,其中 i,j 元素将代表第 i 个标题和第 j 个标题之间的单词差异。

像这样:

    import numpy as np
from itertools import product

l = list(data_sorted['title'])

def diff_words(text_1, text_2):
# return the number of different words between two texts
words_1 = text_1.split()
words_2 = text_2.split()
diff = max(len(words_1),len(words_2))-len(np.intersect1d(words_1, words_2))
return diff


differences = [diff_words(i,j) for i,j in product(l,l)]
# differences: a flat matrix integers where the i,j element is the word difference between titles i and j

关于python - 在Python中删除数据框中的重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51796886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com